1. 依赖包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.1</version>
</dependency>
2. java代码例子
package com.fan.http;
import java.nio.charset.Charset;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientTest {
public static void main(String[] args) {
String url = "http://test.do";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json; charset=utf-8");
StringEntity entity = new StringEntity("{\"userid\":\"test\"}", Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
try {
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(statusCode);
System.out.println(content);
} catch (Exception e) {
e.printStackTrace();
}
}
}