Jakarta Commons HttpClient 3.x上传文件

Android SDK集成了Apache HttpClient模块。要注意的是,这里的Apache HttpClient模块是HttpClient 4.0(org.apache.http.*),,而不是常见的Jakarta Commons HttpClient 3.x(org.apache.commons.httpclient.*)。HttpClient 4.0不能传递文件类型。我们可以使用HttpClient 3.x来实现文件上传。

使用这种方式需要导入 commons-httpclient-3.1.jar  httpmime-4.1.3.jar 和commons-codec-1.3.jar

这些类包可以在我的资源中找到。

单文件上传:

 try {
            HttpClient httpclient = new DefaultHttpClient();
            // 设置通信协议版本
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpPost httppost = new HttpPost(url);

            MultipartEntity mpEntity = new MultipartEntity(); // 文件传输
            mpEntity.addPart("", new FileBody(file));
            mpEntity.addPart("",new StringBody(""));
            httppost.setEntity(mpEntity);

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                Message msg = new Message();
                signTime = ParseXmlUtils.signTime(resEntity.getContent());
                resEntity.consumeContent();
            }
            resEntity.consumeContent();
            httpclient.getConnectionManager().shutdown();

        } catch (Exception e) {
            e.printStackTrace();
            file.delete();
        }


多文件上传:
 for(File file:files){
            PostMethod filePost = new PostMethod("this is url");
            try {
                String fileName ="filename";
                // 组拼post数据的实体
                Part[] parts = { new StringPart("userId", "userId"),
                        new StringPart("fileName", URLEncoder.encode(URLEncoder.encode(fileName, "utf-8"), "utf-8")),
                        new FilePart("file", file),

                };
                filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams()));
                HttpClient client = new HttpClient();
                client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                // 执行文件上传的post请求
                client.executeMethod(filePost);

            } catch (Exception e) {
                e.printStackTrace();

            } finally {
                filePost.releaseConnection();
            }
        }






你可能感兴趣的:(Commons,HttpClient,HTTP)