httpclient发送请求
依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
1.发送带参数的http的get通用请求
public String doGetParms(String url,List<NameValuePair> list) throws IOException {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
String params = EntityUtils.toString(new UrlEncodedFormEntity(list,Consts.UTF_8));
System.out.println("查询执行"+url+"?"+params);
HttpGet httpGet = new HttpGet(url+"?"+params);
httpGet.setHeader("", ""); //根据自己的需要存放请求头参数,可以有多个一般是放Authorization
httpGet.setHeader("","");
String string = "";
CloseableHttpResponse response = null;
try {
response = closeableHttpClient.execute(httpGet); //执行
HttpEntity entity = response.getEntity(); //得到返回的数据
string = EntityUtils.toString(entity, StandardCharsets.UTF_8); //把返回数据转化成字符串,字符集为UTF_8
System.out.println("查询的一个对象返回的string = " + string);
EntityUtils.consume(entity); //确保被消费
}catch (Exception e){
e.printStackTrace();
}finally {
if (response!=null){
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (closeableHttpClient!=null){
try {
closeableHttpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return string;
}
传的参数可以这样传
public void test(){
String url = ""; //根据自己的路径修改url
List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("username","xjq")); //get请求所需要携带的参数放在这里,可以有多个
list.add(new BasicNameValuePair("password","123456"));
try {
doGetParms(url,list);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
2.发送带参数的post请求,参数传参为form-data形式
public String doPost(String url, MultipartEntityBuilder multipartEntityBuilder) throws IOException {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("",""); //根据自己的需要存放请求头参数,可以有多个一般是放Authorization
httpPost.setHeader("","");
multipartEntityBuilder.setContentType(ContentType.create("multipart/form-data", Consts.UTF_8));//设置参数形式form-data
httpPost.setEntity(multipartEntityBuilder.build());
CloseableHttpResponse response = null;
String str = null;
try {
response = closeableHttpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
str = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println("返回的string = " + str);
EntityUtils.consume(entity);
}catch (Exception e){
e.printStackTrace();
}finally {
if (response!=null){
response.close();
}
if (closeableHttpClient!=null){
closeableHttpClient.close();
}
}
return str;
}
传的参数可以这样传
public void test(){
String url = ""; //根据自己的路径修改url
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532); //防止中文乱码
ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
entityBuilder.addTextBody("username","xjq");
entityBuilder.addTextBody("password","123456");
entityBuilder.addTextBody("personName","帅帅的泉",contentType);//如果传的参数是中文记得设置contentType不然传进去是乱码
try {
doPost(url,entityBuilder);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
3.发送带参数的post请求,参数传参为json形式
public String doPostJson(String url, JSONObject jsonObject) throws IOException {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("",""); //根据自己的需要存放请求头参数,可以有多个一般是放Authorization
httpPost.setHeader("","");
StringEntity stringEntity = new StringEntity(jsonObject.toString(),Consts.UTF_8);
stringEntity.setContentType(new BasicHeader("Content-Type","application/json; charset=utf-8"));//设置传参为json形式,字符集为utf-8
stringEntity.setContentEncoding(Consts.UTF_8.name());
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = null;
String str = null;
try {
response = closeableHttpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
str = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println("返回的string = " + str);
EntityUtils.consume(entity);
}catch (Exception e){
e.printStackTrace();
}finally {
if (response!=null){
response.close();
}
if (closeableHttpClient!=null){
closeableHttpClient.close();
}
}
return str;
}
传的参数可以这样传
public void test(){
String url = ""; //根据自己的路径修改url
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","xjq");
jsonObject.put("password","123456");
try {
doPostJson(url,jsonObject);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
4.发送带参数的put请求,参数传参为json形式
public String doPutJson(String url, JSONObject jsonObject) throws IOException {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
httpPut.setHeader("","");
httpPut.setHeader("","");
StringEntity stringEntity = new StringEntity(jsonObject.toString(),Consts.UTF_8);
stringEntity.setContentType(new BasicHeader("Content-Type","application/json; charset=utf-8"));
stringEntity.setContentEncoding(Consts.UTF_8.name());
httpPut.setEntity(stringEntity);
CloseableHttpResponse response = null;
String str = null;
try {
response = closeableHttpClient.execute(httpPut);
HttpEntity entity = response.getEntity();
str = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println("返回的string = " + str);
EntityUtils.consume(entity);
}catch (Exception e){
e.printStackTrace();
}finally {
if (response!=null){
response.close();
}
if (closeableHttpClient!=null){
closeableHttpClient.close();
}
}
return str;
}
传的参数可以这样传
public void test(){
String url = ""; //根据自己的路径修改url
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","xjq");
jsonObject.put("password","123456");
try {
doPostJson(url,jsonObject);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
5.发送带参数的delete请求,参数传参为json形式
1.首先导入自己的delete类
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
public class MyHttpDelete extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
@Override
public String getMethod() {
return METHOD_NAME;
}
public MyHttpDelete(final String uri) {
super();
setURI(URI.create(uri));
}
public MyHttpDelete(final URI uri) {
super();
setURI(uri);
}
public MyHttpDelete() {
super();
}
}
2.发送delete请求
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author xjq
* @version 1.0
* @date 2022/11/3 15:45
*/
public class HttpJsonDel {
public static void main(String[] args) throws IOException {
String url = "http://localhost:8080/Json/del/33";
CloseableHttpClient httpClient = HttpClients.createDefault();
MyHttpDelete httpDelete = new MyHttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(10000).build();
httpDelete.setConfig(requestConfig);
httpDelete.setHeader("Content-type", "application/json");
httpDelete.setHeader("DataEncoding", "UTF-8");
CloseableHttpResponse httpResponse = null;
try {
httpDelete.setEntity(new StringEntity(JSON.toJSONString(null),"UTF-8"));
httpResponse = httpClient.execute(httpDelete);
HttpEntity entity = httpResponse.getEntity();
StringBuilder entityStringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader
(new InputStreamReader(entity.getContent(), "UTF-8"), 8 * 1024);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
entityStringBuilder.append(line);
}
System.out.println("客户端获取响应报文:" + entityStringBuilder.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
利用hutool封装好的方法发送http请求
User实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer userId;
private String userName;
private String password;
}
1.发送带参数的post请求,参数传参为json形式
接口如下:
@PostMapping("http")
public String http(@RequestBody User user){
return "http:用户名:"+ user.getUserName() + " 密码:"+user.getPassword();
}
测试:
//利用hutool发送post带参数(json)请求
JSONObject json = new JSONObject();
json.put("userName", "xjq");
json.put("password", "123456");
String result = HttpRequest.post("http://localhost:8080/test/http")
.header("Content-Type", "application/json")//头信息,多个头信息多次调用此方法即可
.body(String.valueOf(json))
.execute().body();
System.out.println("result = " + result);
2.发送带参数的get请求
接口如下:
@GetMapping("http2")
public String http2(User user){
return "http:用户名:"+ user.getUserName() + " 密码:"+user.getPassword();
}
测试:
//利用hutool发送get带参数请求
Map<String,Object> map = new HashMap<>();
map.put("userName", "xjq");
map.put("password", "123456");
String result2 = HttpRequest.get("http://localhost:8080/test/http2")
.form(map)
.execute().body();
System.out.println("result2 = " + result2);
3.发送带参数的put请求,参数传参为json形式
接口如下:
@PutMapping("http3")
public String http3(@RequestBody User user){
return "http:用户名:"+ user.getUserName() + " 密码:"+user.getPassword();
}
测试:
JSONObject json3 = new JSONObject();
json3.put("userName", "xjq");
json3.put("password", "123456");
String result3 = HttpRequest.put("http://localhost:8080/test/http3")
.header("Content-Type", "application/json")//头信息,多个头信息多次调用此方法即可
.body(String.valueOf(json3))
.execute().body();
System.out.println("result3 = " + result3);
最后结果:
result = http:用户名:xjq 密码:123456
result2 = http:用户名:xjq 密码:123456
result3 = http:用户名:xjq 密码:123456