httpclient5发送post请求,和get请求,java代码详细示例,封装成方法
时间: 2023-05-31 10:02:52 浏览: 54
HttpClient5是Apache HttpClient的最新版本,它提供了许多新的功能和改进。下面是使用HttpClient5发送POST和GET请求的示例代码:
1.发送POST请求
```java
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.StringEntity;
import java.io.IOException;
public class HttpClientUtils {
public static String doPost(String url, String json) {
String result = "";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(json, "UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
try {
result = httpClient.execute(httpPost, response -> {
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
return responseEntity.getContent();
} else {
return null;
}
});
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
```
2.发送GET请求
```java
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.HttpEntity;
import java.io.IOException;
public class HttpClientUtils {
public static String doGet(String url) {
String result = "";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
try {
result = httpClient.execute(httpGet, response -> {
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
return responseEntity.getContent();
} else {
return null;
}
});
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
```
以上代码中,我们使用HttpClient5创建了一个HttpClient对象,然后使用HttpPost或HttpGet方法创建一个请求对象,设置请求参数并执行请求。在执行请求时,我们使用了Java 8中的Lambda表达式来处理响应数据。最后,我们返回响应的字符串结果。