发送指定form-data数据

之前遇到在java 后台发送form-data 格式数据到PHP接口的问题,找了好多方法都没行的通,后来看到一个很好的方法,才发现想要发送form-data 格式的数据,每个参数之间的书需要分隔的,卡了很久......

 // 每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
    private static final String BOUNDARY = "----------HV2ymHFg03ehbqgZCaKO6jyH";

    public static String sendHttpPostRequest(String serverUrl,
                                      ArrayList<FormFieldKeyValuePair> generalFormFields
            ) 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();
        // 处理文字形式的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"));
        out.write(endBoundary.getBytes("utf-8"));
        out.flush();
        out.close();

        // 从服务器获得回答的内容
        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;

    }
同时,该方法还可以添加上传文件的功能

 //  处理文件上传 需要传一个ArrayList<UploadFileItem> filesToBeUploaded参数
       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"));
form 键值对实体类

@ToString
@Setter@Getter
@AllArgsConstructor
public class FormFieldKeyValuePair {
    private static final long serialVersionUID = 1L;
    private String key;
    private Object value;
}
form 文件实体类

@ToString
@Setter@Getter
@AllArgsConstructor
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;

}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值