java发送form-data 格式post请求

HttpPost httpPost = new HttpPost(***);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();

builder.addTextBody("account",*** );
builder.addTextBody("password",*** );
HttpEntity multipart = builder.build();
String responseJson = HttpUtil.postSet(multipart, httpPost);

 

 

  /***
     * 
     * @Description post请求
     * @Date 14:35 2020/9/25
     * @Param [stringBuilder, params]
     * @return java.lang.String
     **/
    public static String postSet(HttpEntity params, HttpPost httpPost) throws IOException {
        httpPost.setEntity(params);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            return result;
        }
        return null;
    }
  • 7
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
好的,让我来回答你的问题。Java发送form-data请求可以采用Apache HttpComponents库的MultipartEntityBuilder类。以下是一个示例代码: ``` import java.io.File; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class FormDataRequestDemo { public static void main(String[] args) throws ClientProtocolException, IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/upload"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("username", "john"); builder.addTextBody("password", "password123"); builder.addBinaryBody("file", new File("/path/to/myfile"), ContentType.DEFAULT_BINARY, "myfile.txt"); HttpEntity entity = builder.build(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { System.out.println("Response content: " + EntityUtils.toString(responseEntity)); } } } ``` 在这个示例代码中,我们使用了MultipartEntityBuilder类来构建一个multipart/form-data请求实体,并将其设置为HttpPost对象的请求实体。我们添加了一个普通文本部分("username"和"password"),以及一个二进制部分("file")。最后我们执行HttpPost请求,并从响应实体中读取并打印出响应内容。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值