(一)相关jar包坐标
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
(二)编写代码
public static void doJsonPost(String uri, String params) {
HttpPost post = new HttpPost(uri);
post.setHeader("X-Lemonban-Media-Type", "lemonban.v1");
post.setHeader("Content-Type", "application/json");
try {
post.setEntity(new StringEntity(params, "utf-8"));
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(post);
getCodeAndResult(response);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void doFormPost(String uri, String params) {
HttpPost post = new HttpPost(uri);
post.setHeader("X-Lemonban-Media-Type", "lemonban.v1");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
post.setEntity(new StringEntity(params, "utf-8"));
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(post);
getCodeAndResult(response);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void getCodeAndResult(HttpResponse response) throws IOException {
int code = response.getStatusLine().getStatusCode();
System.out.println(code);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
}