`

HttpClient模拟表单multipart/form-data方式上传文件和参数

 
阅读更多
原文地址:http://woxiangbo.iteye.com/blog/1751740




主要有三个类,亲试成功:
HttpPostEmulator:

Java代码  收藏代码
import java.io.BufferedReader; 
import java.io.DataInputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.Serializable; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.ArrayList; 
 
public class HttpPostEmulator { 
    // 每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。 
    private static final String BOUNDARY = "----------HV2ymHFg03ehbqgZCaKO6jyH"; 
 
    public String sendHttpPostRequest(String serverUrl, 
            ArrayList<FormFieldKeyValuePair> generalFormFields, 
            ArrayList<UploadFileItem> filesToBeUploaded) throws Exception { 
 
        // 向服务器发送post请求 
 
        URL url = new URL(serverUrl/* "http://127.0.0.1:8080/test/upload" */); 
 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
 
        // 发送POST请求必须设置如下两行 
 
        connection.setDoOutput(true); 
        connection.setDoInput(true); 
        connection.setUseCaches(false); 
        connection.setRequestMethod("POST"); 
        connection.setRequestProperty("Connection", "Keep-Alive"); 
        connection.setRequestProperty("Charset", "UTF-8"); 
        connection.setRequestProperty("Content-Type", 
                "multipart/form-data; boundary=" + BOUNDARY); 
 
        // 头 
 
        String boundary = BOUNDARY; 
 
        // 传输内容 
 
        StringBuffer contentBody = new StringBuffer("--" + BOUNDARY); 
 
        // 尾 
 
        String endBoundary = "\r\n--" + boundary + "--\r\n"; 
 
        OutputStream out = connection.getOutputStream(); 
 
        // 1. 处理文字形式的POST请求 
 
        for (FormFieldKeyValuePair ffkvp : generalFormFields) 
 
        { 
 
            contentBody.append("\r\n") 
 
            .append("Content-Disposition: form-data; name=\"") 
 
            .append(ffkvp.getKey() + "\"") 
 
            .append("\r\n") 
 
            .append("\r\n") 
 
            .append(ffkvp.getValue()) 
 
            .append("\r\n") 
 
            .append("--") 
 
            .append(boundary); 
 
        } 
 
        String boundaryMessage1 = contentBody.toString(); 
 
        out.write(boundaryMessage1.getBytes("utf-8")); 
 
        // 2. 处理文件上传 
 
        for (UploadFileItem ufi : filesToBeUploaded) 
 
        { 
 
            contentBody = new StringBuffer(); 
 
            contentBody.append("\r\n") 
 
            .append("Content-Disposition:form-data; name=\"") 
 
            .append(ufi.getFormFieldName() + "\"; ") // form中field的名称 
 
                    .append("filename=\"") 
 
                    .append(ufi.getFileName() + "\"") // 上传文件的文件名,包括目录 
 
                    .append("\r\n") 
 
                    .append("Content-Type:application/octet-stream") 
 
                    .append("\r\n\r\n"); 
 
            String boundaryMessage2 = contentBody.toString(); 
 
            out.write(boundaryMessage2.getBytes("utf-8")); 
 
            // 开始真正向服务器写文件 
 
            File file = new File(ufi.getFileName()); 
 
            DataInputStream dis = new DataInputStream(new FileInputStream(file)); 
 
            int bytes = 0; 
 
            byte[] bufferOut = new byte[(int) file.length()]; 
 
            bytes = dis.read(bufferOut); 
 
            out.write(bufferOut, 0, bytes); 
 
            dis.close(); 
 
            contentBody.append("------------HV2ymHFg03ehbqgZCaKO6jyH"); 
 
            String boundaryMessage = contentBody.toString(); 
 
            out.write(boundaryMessage.getBytes("utf-8")); 
 
            // System.out.println(boundaryMessage); 
 
        } 
 
        out.write("------------HV2ymHFg03ehbqgZCaKO6jyH--\r\n" 
                .getBytes("UTF-8")); 
 
        // 3. 写结尾 
 
        out.write(endBoundary.getBytes("utf-8")); 
 
        out.flush(); 
 
        out.close(); 
 
        // 4. 从服务器获得回答的内容 
 
        String strLine = ""; 
 
        String strResponse = ""; 
 
        InputStream in = connection.getInputStream(); 
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
 
        while ((strLine = reader.readLine()) != null) 
 
        { 
 
            strResponse += strLine + "\n"; 
 
        } 
 
        // System.out.print(strResponse); 
 
        return strResponse; 
 
    } 
 

FormFieldKeyValuePair:

Java代码  收藏代码
public class FormFieldKeyValuePair { 
    private static final long serialVersionUID = 1L; 
 
    // The form field used for receivinguser's input, 
 
    // such as "username" in "<inputtype="text" name="username"/>" 
 
    private String key; 
 
    // The value entered by user in thecorresponding form field, 
 
    // such as "Patrick" the abovementioned formfield "username" 
 
    private String value; 
 
    public FormFieldKeyValuePair(String key, String value) 
 
    { 
 
        this.key = key; 
 
        this.value = value; 
 
    } 
 
    public String getKey() 
 
    { 
 
        return key; 
 
    } 
 
    public void setKey(String key) { 
 
        this.key = key; 
 
    } 
 
    public String getValue() 
 
    { 
 
        return value; 
 
    } 
 
    public void setValue(String value) 
 
    { 
 
        this.value = value; 
 
    } 

UploadFileItem:

Java代码  收藏代码
public class UploadFileItem implements Serializable{ 
    private static final long serialVersionUID = 1L; 
 
    // The form field name in a form used foruploading a file, 
 
    // such as "upload1" in "<inputtype="file" name="upload1"/>" 
 
    private String formFieldName; 
 
    // File name to be uploaded, thefileName contains path, 
 
    // such as "E:\\some_file.jpg" 
 
    private String fileName; 
 
    public UploadFileItem(String formFieldName, String fileName) 
 
    { 
 
        this.formFieldName = formFieldName; 
 
        this.fileName = fileName; 
 
    } 
 
    public String getFormFieldName() 
 
    { 
 
        return formFieldName; 
 
    } 
 
    public void setFormFieldName(String formFieldName) 
 
    { 
 
        this.formFieldName = formFieldName; 
 
    } 
 
    public String getFileName() 
 
    { 
 
        return fileName; 
 
    } 
 
    public void setFileName(String fileName) 
 
    { 
 
        this.fileName = fileName; 
 
    } 

Test:

Java代码  收藏代码
public class UploadImage_Test { 
    @Test 
    public void normal() throws Exception { 
        // 设定服务地址 
        String serverUrl = "http://xxxxxxxxxxxxxxxx";//上传地址 
         
        // 设定要上传的普通Form Field及其对应的value 
        ArrayList<FormFieldKeyValuePair> ffkvp = new ArrayList<FormFieldKeyValuePair>(); 
        ffkvp.add(new FormFieldKeyValuePair("phone", "123456789"));//其他参数 
        String receive1=RandomUtils.getRandomPhone(); 
        String receive2=RandomUtils.getRandomPhone(); 
        ffkvp.add(new FormFieldKeyValuePair("receiver", receive1+"|"+receive2)); 
        ffkvp.add(new FormFieldKeyValuePair("type", "png")); 
 
        // 设定要上传的文件 
        ArrayList<UploadFileItem> ufi = new ArrayList<UploadFileItem>(); 
        ufi.add(new UploadFileItem("image", System.getProperty("user.dir")+"/src/test/resources/123.jpg")); 
        HttpPostEmulator hpe = new HttpPostEmulator(); 
        String response = hpe.sendHttpPostRequest(serverUrl, ffkvp, ufi); 
        System.out.println("Responsefrom server is: " + response); 
         
        //对 imageUrl、thumbnailUrl、shortUrl进行获取,不能返回空 
        HttpClient httpClient = new HttpClient(); 
            GetMethod getMethod = new GetMethod(imageUrl); 
            if (httpClient.executeMethod(getMethod) != HttpStatus.SC_OK) { 
                Assert.fail("imageUrl 内容不存在."); 
            } 
       
         } 
    } 
分享到:
评论

相关推荐

    c#实现HttpClient拼接multipart/form-data形式参数post提交数据

    使用c#实现的HttpClient拼接multipart/form-data形式参数post提交数据,包含图片内容,有需要的可以下载,希望能帮到有需要的人,

    ASP.NET-WebApi-MultipartDataMediaFormatter:用于在发送和接收多部分编码的表单数据时绑定自定义类型(包括文件)

    ASP.NET WebApi MultipartDataMediaFormatter 这是编码为multipart / form-data的自定义类型(包括文件)的自动绑定操作参数的解决方案。 它的工作方式类似于ASP.NET MVC绑定。 此媒体类型格式化程序也可以用于发送...

    httpclient-4.5.13-API文档-中文版.zip

    赠送jar包:httpclient-4.5.13.jar; 赠送原API文档:httpclient-4.5.13-javadoc.jar; 赠送源代码:httpclient-4.5.13-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.13.pom; 包含翻译后的API文档:...

    .NET Core使用HttpClient进行表单提交时遇到的问题

    在微信支付接口文档也说明了,需要使用 multipart/form-data 的方式发送请求。.NET 提供了 MultipartFormDataContent 类型,帮助我们构建表单请求,故有以下代码: var form = new MultipartFormDataContent() { {...

    httpclient-4.5.6-API文档-中文版.zip

    赠送jar包:httpclient-4.5.6.jar; 赠送原API文档:httpclient-4.5.6-javadoc.jar; 赠送源代码:httpclient-4.5.6-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.6.pom; 包含翻译后的API文档:httpclient...

    HttpClientUtil 类

    包含普通http的get和post传输方式,还包含multipart/form-data方式的post传输方式。

    httpclient-4.5.12-API文档-中英对照版.zip

    赠送jar包:httpclient-4.5.12.jar; 赠送原API文档:httpclient-4.5.12-javadoc.jar; 赠送源代码:httpclient-4.5.12-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.12.pom; 包含翻译后的API文档:...

    httpclient-4.5.6-API文档-中英对照版.zip

    赠送jar包:httpclient-4.5.6.jar; 赠送原API文档:httpclient-4.5.6-javadoc.jar; 赠送源代码:httpclient-4.5.6-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.6.pom; 包含翻译后的API文档:httpclient...

    HttpClient--最全--安装包+官方文档(中文)

    HttpClient--最全--安装包+官方文档(中文),HttpClient--最全--安装包+官方文档(中文)

    springmvc和mybatis集成全部jar包(全)

    springmvc4.3.3和mybatis3.4.1集成最新全部jar包,还包含了其他一些常用的jar包,很全,已经在项目中验证过。 lib/antlr-2.7.2.jar lib/aopalliance-1.0.jar lib/asm-3.3.1.jar lib/aspectjweaver-1.6.5.jar ...

    httpclient-4.5.13-API文档-中英对照版.zip

    赠送jar包:httpclient-4.5.13.jar; 赠送原API文档:httpclient-4.5.13-javadoc.jar; 赠送源代码:httpclient-4.5.13-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.13.pom; 包含翻译后的API文档:...

    httpclient-4.5.3-API文档-中英对照版.zip

    赠送jar包:httpclient-4.5.3.jar; 赠送原API文档:httpclient-4.5.3-javadoc.jar; 赠送源代码:httpclient-4.5.3-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.3.pom; 包含翻译后的API文档:httpclient...

    commons-httpclient-3.0.1--java网络开发

    package org.apache.commons.httpclient; // Imports import java.io.IOException; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.logging.Log; public class ...

    httpclient-4.4.1-API文档-中文版.zip

    赠送jar包:httpclient-4.4.1.jar; 赠送原API文档:httpclient-4.4.1-javadoc.jar; 赠送源代码:httpclient-4.4.1-sources.jar; 赠送Maven依赖信息文件:httpclient-4.4.1.pom; 包含翻译后的API文档:httpclient...

    httpclient-4.5.5-API文档-中文版.zip

    赠送jar包:httpclient-4.5.5.jar; 赠送原API文档:httpclient-4.5.5-javadoc.jar; 赠送源代码:httpclient-4.5.5-sources.jar; 包含翻译后的API文档:httpclient-4.5.5-javadoc-API文档-中文(简体)版.zip ...

    httpclient-4.5.12-API文档-中文版.zip

    赠送jar包:httpclient-4.5.12.jar; 赠送原API文档:httpclient-4.5.12-javadoc.jar; 赠送源代码:httpclient-4.5.12-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.12.pom; 包含翻译后的API文档:...

    httpclient-4.4-API文档-中文版.zip

    赠送jar包:httpclient-4.4.jar; 赠送原API文档:httpclient-4.4-javadoc.jar; 赠送源代码:httpclient-4.4-sources.jar; 赠送Maven依赖信息文件:httpclient-4.4.pom; 包含翻译后的API文档:httpclient-4.4-...

    httpclient-4.5.10-API文档-中文版.zip

    赠送jar包:httpclient-4.5.10.jar; 赠送原API文档:httpclient-4.5.10-javadoc.jar; 赠送源代码:httpclient-4.5.10-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.10.pom; 包含翻译后的API文档:...

    wechatpay-apache-httpclient-0.2.1.jar

    wechatpay-apache-httpclient-0.2.1.jar

    httpclient-4.2.5-API文档-中文版.zip

    赠送jar包:httpclient-4.2.5.jar; 赠送原API文档:httpclient-4.2.5-javadoc.jar; 赠送源代码:httpclient-4.2.5-sources.jar; 赠送Maven依赖信息文件:httpclient-4.2.5.pom; 包含翻译后的API文档:httpclient...

Global site tag (gtag.js) - Google Analytics