如何通过http客户端4.5.2发送POST请求

时间:2017-07-01 09:25:44

标签: java httpclient

我使用http客户端发送HTTP Post请求,如下所示。

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.2</version>
</dependency>

服务器需要一些params inclue:method(String),appKey(String),signMethod(String),img(byte [])..

我使用以下代码发送帖子,但响应显示:&#34;缺少必需的参数:img&#34;。

// append URL
String fullUrl = HttpRequestUtils.appendUrlRequestParams(API, params);

// builder request entity
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(Charset.forName("UTF-8"));
for(Entry<String, String> entry : params.entrySet()) {
    multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue());
}
multipartEntityBuilder.addBinaryBody(PictureUploadConstant.img, imgs);
HttpEntity requestEntity = multipartEntityBuilder.build();

// post
HttpPost post = new HttpPost(fullUrl);
post.setEntity(requestEntity);

CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
    // send post
    response = httpClient.execute(post);
    // response
    HttpEntity responseEntity = response.getEntity();
    String result = EntityUtils.toString(responseEntity);
    System.out.println("result" + result);
} catch (IOException e) {
    e.printStackTrace();
}

任何人都可以告诉我它有什么问题吗?

0 个答案:

没有答案