閫氳繃鏋勯€犲熀浜?HTTP 鍗忚鐨勪紶杈撳唴瀹瑰疄鐜板浘鐗囪嚜鍔ㄤ笂浼犲埌鏈嶅姟鍣ㄥ姛鑳?銆傚鏋滆嚜宸辩紪鐮佹瀯閫?HTTP 鍗忚锛岄偅涔堢紪鍐欑殑浠g爜璐ㄩ噺鑲畾涓嶉珮锛屽缓璁ā浠?HttpClient .zip examples \mime\ClientMultipartFormPost.java 鏉ュ疄鐜帮紝骞堕€氳繃婧愮爜鏉ヨ繘涓€姝ョ悊瑙e浣曚紭闆呴珮鏁堝湴鏋勯€?HTTP 鍗忚浼犺緭鍐呭銆?/span>

鑷繁鏋勯€?HTTP 鍗忚浼犺緭鍐呭鐨勬兂娉曪紝浠庝綍鑰屾潵鍛紵鐏垫劅鍚开浜庤繖绡囧崥鏂団€?a href="http://blog.csdn.net/newjueqi/archive/2009/11/06/4777779.aspx">Android涓嬬殑搴旂敤缂栫▼鈥斺€旂敤HTTP鍗忚瀹炵幇鏂囦欢涓婁紶鍔熻兘 鈥濓紝浠ュ墠浠庢湭鎯宠繃閫氳繃鎶撳彇 HTTP 璇锋眰鏁版嵁鏍煎紡锛屾牴鎹崗璁嚜宸辨瀯閫犳暟鎹潵瀹炵幇鏁版嵁鎻愪氦銆傚搸锛孫ut 浜嗐€傚洜涓?Apache HttpClient 妗嗘灦灏辨槸閫氳繃姝ゆ柟寮忔潵瀹炵幇鐨勶紝浠ュ墠浠庢湭娉ㄦ剰鍒帮紝鐪嬫潵浠ュ悗瑕佸澶氬悜鍓嶄汉瀛︿範鍟婏紒缁撴灉鏄細闃呰浜嗘妗嗘灦鐨勬簮鐮佸悗锛屾墠鐭ラ亾鑷繁缂栧啓鐨勪唬鐮佸拰浜哄鐩告瘮鐪熶笉鏄竴涓。娆$殑銆傜幇鍦ㄥ凡缁忎笅瀹氬喅蹇冧簡锛屽璇诲紑婧愭鏋朵唬鐮侊紝涓嶄絾鍙互鐔熸倝鐩稿叧涓氬姟娴佺▼锛岃€屼笖杩樺彲浠ュ鍒拌璁℃ā寮忓湪瀹為檯涓氬姟闇€姹備腑鐨勫簲鐢紝鏇撮噸瑕佺殑鏄鎮熷叾涓殑鎬濇兂銆備笟鍔℃祦绋嬨€佸疄璺佃兘鍔涖€佹鏋舵€濇兂锛屼竴涓句笁寰楋紝浣曚箰鑰屼笉涓哄憿銆俕_^

test.html 閮ㄥ垎婧愮爜锛?/span>

<form action="Your_Action_Url " method="post" enctype="multipart/form-data " name="form1" id="form1">
<p>
<label for="upload_file"></label>
<input type="file" name="upload_file" id="upload_file " />
</p>
<p>
<input type="submit" name="action" id="action " value="upload " />
</p>
</form>

閫氳繃 HttpWatch 鏌ョ湅鎶撳彇鍒扮殑鍖呮暟鎹牸寮忥細

涓嬮潰灏嗗垎鍒€氳繃鎸夌収 HttpWatch 鎶撳彇涓嬫潵鐨勫崗璁牸寮忓唴瀹规瀯閫犱紶杈撳唴瀹瑰疄鐜版枃浠朵笂浼犲姛鑳藉拰鍩轰簬 HttpClient 妗嗘灦瀹炵幇鏂囦欢涓婁紶鍔熻兘銆?/span>

椤圭洰閰嶇疆鐩綍Your_Project/config 锛岀浉鍏虫枃浠?/span> 濡備笅锛?/span>

actionUrl.properties 鏂囦欢鍐呭锛?/span>

Your_Action_Url

formDataParams.properties 鏂囦欢鍐呭锛堝搴?HTML Form 灞炴€у唴瀹癸級锛?/span>

action =upload

imageParams.properties 鏂囦欢鍐呭锛堣繖閲屾枃浠惰矾寰勫凡閰嶇疆姝讳簡锛屼笉濂斤紒寤鸿鍦ㄧ▼搴忎腑鍔ㄦ€佽缃紝鍗抽€氳繃浼犲叆鐩稿叧鍙傛暟瀹炵幇銆傦級锛?/span>

upload_file =images/roewe.jpg

MIMETypes.properties 鏂囦欢鍐呭锛堝弬鑰冭嚜 Multimedia MIME Reference 锛夛細

jpeg:image/jpeg
jpg:image/jpeg
png:image/png
gif:image/gif

1. 鍦ㄣ€?a href="http://blog.csdn.net/newjueqi/archive/2009/11/06/4777779.aspx" target="_blank">Android涓嬬殑搴旂敤缂栫▼鈥斺€旂敤HTTP鍗忚瀹炵幇鏂囦欢涓婁紶鍔熻兘 銆嬩唬鐮佺殑鍩虹涓婏紝閫氳繃杩涗竴姝ユ敼杩涘緱鍒板涓嬩唬鐮侊紙Java銆丄ndroid 閮藉彲浠?run锛夛細

/** * 鏂囦欢鍚嶇О锛歎ploadImage.java * * 鐗堟潈淇℃伅锛欰pache License, Version 2.0 * * 鍔熻兘鎻忚堪锛氬疄鐜板浘鐗囨枃浠朵笂浼犮€? * * 鍒涘缓鏃ユ湡锛?011-5-10 * * 浣滆€咃細Bert Lee *//* * 淇敼鍘嗗彶锛? */public class UploadImage {    String multipart_form_data = "multipart/form-data";    String twoHyphens = "--";    String boundary = "****************fD4fH3gL0hK7aI6";    // 鏁版嵁鍒嗛殧绗?    String lineEnd = System.getProperty("line.separator");    // The value is "\r\n" in Windows.        /*     * 涓婁紶鍥剧墖鍐呭锛屾牸寮忚鍙傝€僅TTP 鍗忚鏍煎紡銆?     * 浜轰汉缃慞hotos.upload涓殑鈥濈▼搴忚皟鐢ㄢ€渉ttp://wiki.dev.renren.com/wiki/Photos.upload#.E7.A8.8B.E5.BA.8F.E8.B0.83.E7.94.A8     * 瀵瑰叾鏍煎紡瑙i噴鐨勯潪甯告竻鏅般€?     * 鏍煎紡濡備笅鎵€绀猴細     * --****************fD4fH3hK7aI6     * Content-Disposition: form-data; name="upload_file"; filename="apple.jpg"     * Content-Type: image/jpeg     *     * 杩欏効鏄枃浠剁殑鍐呭锛屼簩杩涘埗娴佺殑褰㈠紡     */    private void addImageContent(Image[] files, DataOutputStream output) {        for(Image file : files) {            StringBuilder split = new StringBuilder();            split.append(twoHyphens + boundary + lineEnd);            split.append("Content-Disposition: form-data; name=\"" + file.getFormName() + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd);            split.append("Content-Type: " + file.getContentType() + lineEnd);            split.append(lineEnd);            try {                // 鍙戦€佸浘鐗囨暟鎹?                output.writeBytes(split.toString());                output.write(file.getData(), 0, file.getData().length);                output.writeBytes(lineEnd);            } catch (IOException e) {                throw new RuntimeException(e);            }        }    }        /*     * 鏋勫缓琛ㄥ崟瀛楁鍐呭锛屾牸寮忚鍙傝€僅TTP 鍗忚鏍煎紡锛堢敤FireBug鍙互鎶撳彇鍒扮浉鍏虫暟鎹級銆?浠ヤ究涓婁紶琛ㄥ崟鐩稿搴旂殑鍙傛暟鍊?     * 鏍煎紡濡備笅鎵€绀猴細     * --****************fD4fH3hK7aI6     * Content-Disposition: form-data; name="action"     * // 涓€绌鸿锛屽繀椤绘湁     * upload     */    private void addFormField(Set<Map.Entry<Object,Object>> params, DataOutputStream output) {        StringBuilder sb = new StringBuilder();        for(Map.Entry<Object, Object> param : params) {            sb.append(twoHyphens + boundary + lineEnd);            sb.append("Content-Disposition: form-data; name=\"" + param.getKey() + "\"" + lineEnd);            sb.append(lineEnd);            sb.append(param.getValue() + lineEnd);        }        try {            output.writeBytes(sb.toString());// 鍙戦€佽〃鍗曞瓧娈垫暟鎹?        } catch (IOException e) {            throw new RuntimeException(e);        }    }        /**     * 鐩存帴閫氳繃 HTTP 鍗忚鎻愪氦鏁版嵁鍒版湇鍔″櫒锛屽疄鐜拌〃鍗曟彁浜ゅ姛鑳姐€?     * @param actionUrl 涓婁紶璺緞     * @param params 璇锋眰鍙傛暟key涓哄弬鏁板悕锛寁alue涓哄弬鏁板€?     * @param files 涓婁紶鏂囦欢淇℃伅     * @return 杩斿洖璇锋眰缁撴灉     */    public String post(String actionUrl, Set<Map.Entry<Object,Object>> params, Image[] files) {        HttpURLConnection conn = null;        DataOutputStream output = null;        BufferedReader input = null;        try {            URL url = new URL(actionUrl);            conn = (HttpURLConnection) url.openConnection();            conn.setConnectTimeout(120000);            conn.setDoInput(true);        // 鍏佽杈撳叆            conn.setDoOutput(true);        // 鍏佽杈撳嚭            conn.setUseCaches(false);    // 涓嶄娇鐢–ache            conn.setRequestMethod("POST");            conn.setRequestProperty("Connection", "keep-alive");            conn.setRequestProperty("Content-Type", multipart_form_data + "; boundary=" + boundary);                        conn.connect();            output = new DataOutputStream(conn.getOutputStream());                        addImageContent(files, output);    // 娣诲姞鍥剧墖鍐呭                        addFormField(params, output);    // 娣诲姞琛ㄥ崟瀛楁鍐呭                        output.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);// 鏁版嵁缁撴潫鏍囧織            output.flush();                        int code = conn.getResponseCode();            if(code != 200) {                throw new RuntimeException("璇锋眰鈥? + actionUrl +"鈥欏け璐ワ紒");            }                        input = new BufferedReader(new InputStreamReader(conn.getInputStream()));            StringBuilder response = new StringBuilder();            String oneLine;            while((oneLine = input.readLine()) != null) {                response.append(oneLine + lineEnd);            }                        return response.toString();        } catch (IOException e) {            throw new RuntimeException(e);        } finally {            // 缁熶竴閲婃斁璧勬簮            try {                if(output != null) {                    output.close();                }                if(input != null) {                    input.close();                }            } catch (IOException e) {                throw new RuntimeException(e);            }                        if(conn != null) {                conn.disconnect();            }        }    }        public static void main(String[] args) {        try {            String response = "";                        BufferedReader in = new BufferedReader(new FileReader("config/actionUrl.properties"));            String actionUrl = in.readLine();                        // 璇诲彇琛ㄥ崟瀵瑰簲鐨勫瓧娈靛悕绉板強鍏跺€?            Properties formDataParams = new Properties();            formDataParams.load(new FileInputStream(new File("config/formDataParams.properties")));            Set<Map.Entry<Object,Object>> params = formDataParams.entrySet();                        // 璇诲彇鍥剧墖鎵€瀵瑰簲鐨勮〃鍗曞瓧娈靛悕绉板強鍥剧墖璺緞            Properties imageParams = new Properties();            imageParams.load(new FileInputStream(new File("config/imageParams.properties")));            Set<Map.Entry<Object,Object>> images = imageParams.entrySet();            Image[] files = new Image[images.size()];            int i = 0;            for(Map.Entry<Object,Object> image : images) {                Image file = new Image(image.getValue().toString(), image.getKey().toString());                files[i++] = file;            }//            Image file = new Image("images/apple.jpg", "upload_file");//            Image[] files = new Image[0];//            files[0] = file;                        response = new UploadImage().post(actionUrl, params, files);            System.out.println("杩斿洖缁撴灉锛? + response);        } catch (IOException e) {            e.printStackTrace();        }    }}


2. 鍩轰簬 HttpClient 妗嗘灦瀹炵幇鏂囦欢涓婁紶锛屽疄渚嬩唬鐮佸涓嬶細

/** * 鏂囦欢鍚嶇О锛欳lientMultipartFormPost.java * * 鐗堟潈淇℃伅锛欰pache License, Version 2.0 * * 鍔熻兘鎻忚堪锛氶€氳繃 HttpClient 4.1.1 瀹炵幇鏂囦欢涓婁紶銆? * * 鍒涘缓鏃ユ湡锛?011-5-15 * * 浣滆€咃細Bert Lee *//* * 淇敼鍘嗗彶锛? */public class ClientMultipartFormPost {    /**     * 鐩存帴閫氳繃 HttpMime's MultipartEntity 鎻愪氦鏁版嵁鍒版湇鍔″櫒锛屽疄鐜拌〃鍗曟彁浜ゅ姛鑳姐€?     * @return Post 璇锋眰鎵€杩斿洖鐨勫唴瀹?     */    public static String filePost() {        HttpClient httpclient = new DefaultHttpClient();                try {            BufferedReader in = new BufferedReader(new FileReader("config/actionUrl.properties"));            String actionUrl;            actionUrl = in.readLine();            HttpPost httppost = new HttpPost(actionUrl);                        // 閫氳繃闃呰婧愮爜鍙煡锛岃鎯冲疄鐜板浘鐗囦笂浼犲姛鑳斤紝蹇呴』灏?MultipartEntity 鐨勬ā寮忚缃负 BROWSER_COMPATIBLE 銆?            MultipartEntity multiEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);//            MultipartEntity multiEntity = new MultipartEntity();                        // 璇诲彇鍥剧墖鐨?MIME Type 绫诲瀷闆?            Properties mimeTypes = new Properties();            mimeTypes.load(new FileInputStream(new File("config/MIMETypes.properties")));                        // 鏋勯€犲浘鐗囨暟鎹?            Properties imageParams = new Properties();            imageParams.load(new FileInputStream(new File("config/imageParams.properties")));            String fileType;            for(Map.Entry<Object,Object> image : imageParams.entrySet()) {                String path = image.getValue().toString();                fileType = path.substring(path.lastIndexOf(".") + 1);                FileBody binaryContent = new FileBody(new File(path), mimeTypes.get(fileType).toString());//                FileBody binaryContent = new FileBody(new File(path));                multiEntity.addPart(image.getKey().toString(), binaryContent);            }                        // 鏋勯€犺〃鍗曞弬鏁版暟鎹?            Properties formDataParams = new Properties();            formDataParams.load(new FileInputStream(new File("config/formDataParams.properties")));            for(Entry<Object, Object> param : formDataParams.entrySet()) {                multiEntity.addPart(param.getKey().toString(), new StringBody(param.getValue().toString()));            }                        httppost.setEntity(multiEntity);//            Out.println("executing request " + httppost.getRequestLine());                        HttpResponse response = httpclient.execute(httppost);            HttpEntity resEntity = response.getEntity();            //            Out.println("-------------------");//            Out.println(response.getStatusLine());            if(resEntity != null) {                String returnContent = EntityUtils.toString(resEntity);                EntityUtils.consume(resEntity);                                return returnContent; // 杩斿洖椤甸潰鍐呭            }        } catch (IOException e) {            e.printStackTrace();        } finally {            // 閲婃斁璧勬簮            httpclient.getConnectionManager().shutdown();        }        return null;    }    // 娴嬭瘯    public static void main(String[] args) {        Out.println("Response content: " + ClientMultipartFormPost.filePost());    }}

鍙傝€冭祫鏂欙細

  • Android涓嬬殑搴旂敤缂栫▼鈥斺€旂敤HTTP鍗忚瀹炵幇鏂囦欢涓婁紶鍔熻兘
  • How to upload a file using Java HttpClient library


更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. Android进程管理机制及优化(HTC&其它可参
  2. Activity生命周期
  3. Android(安卓)下交叉编译使用(Android(安
  4. android的wifi网卡移植详细过程已经通用
  5. Android(安卓)最火的快速开发框架XUtils
  6. android RelativeLayout属性及demo
  7. 【苦读官方文档】2.Android应用程序基本
  8. Android中的Shape使用总结—圆角的按钮
  9. Android(安卓)的网络编程
  10. Android核心分析 之十一-------Android(