问题
今天遇到一个问题,就是需要发送Http请求去获取一些数据。具体的逻辑是先发起POST请求携带 header 头信息,获取 token,然后携带这个 token 再发送一个GET请求获取数据。
实现
1、导入依赖
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</dependency>
<!-- hutool工具包 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.0</version>
</dependency>
2、工具类
public class HttpUtils {
/**
* 获取响应体信息
*
* @param url 请求的url
* @return /
*/
public static String getToken(String url) {
Map<String, String> headerMap = new HashMap<>();
headerMap.put("x-csrf-token", "fetch");
headerMap.put("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString(("NEW_INTEGRATION" + ":" + "hSsunFUmVpcdaAiMBjEwtCMpFzkuh[xu4xJxZACB").getBytes()));
HttpResponse httpResponse = HttpUtil.createGet(url).addHeaders(headerMap).execute();
List<String> stringList = httpResponse.headers().get("x-csrf-token");
String token = "";
if (stringList != null && stringList.size() != 0) {
token = stringList.get(0);
}
return token;
}
/**
* get请求方式请求url,map是携带的参数?形式
* @param url 请求地址
* @param map 参数 ?传参的形式
* @return /
*/
public static String getXML(String url, Map<String, Object> map) {
HashMap<String, String> headers = new HashMap<>();
headers.put("x-csrf-token", getToken(url));
headers.put("Content-Type", "application/json;charset=UTF-8");
String body = HttpUtil.createGet(url).addHeaders(headers).form(map).execute().body();
return body;
}
/**
* post形式请求url,o是需要传递过来的对象
* @param url 请求地址
* @param o 对象
* @return /
*/
public static String postObject(String url, Object o) {
HashMap<String, String> headers = new HashMap<>();
headers.put("x-csrf-token", getToken(url));
headers.put("Content-Type", "application/json;charset=UTF-8");
String result = HttpUtil.createPost(url).addHeaders(headers).contentType("application/json").body(JSONUtil.toJsonStr(o)).execute().body();
return result;
}
public static String postString(String url, String s) {
HashMap<String, String> headers = new HashMap<>();
headers.put("x-csrf-token", getToken(url));
headers.put("Content-Type", "application/json;charset=UTF-8");
String result = HttpUtil.createPost(url).addHeaders(headers).contentType("application/json").body(s).execute().body();
return result;
}
}
下面是解析xml的方法
public static void main(String[] args) {
String url = "http://localhost:8080/test";
User user = new User("占山", 1);
String s = postXML(url, user);
System.out.println(s);
Map<String, Object> map = new HashMap<>();
// map.put("$expand", "to_Description");
// map.put("$filter", "CreationDate eq datetime'2022-06-30T00:00:00' or LastChangeDate eq datetime'2022-06-30T00:00:00'");
//
// String xml = getXML(url, map);
// System.out.println(xml);
//
// JSONObject jsonObject = JSON.parseObject(xml);
//
// JSONArray jsonArray = jsonObject.getJSONObject("d").getJSONArray("results");
// //遍历
// for (int i = 0; i < jsonArray.size(); i++) {
// com.alibaba.fastjson.JSONObject k3Data = (com.alibaba.fastjson.JSONObject) jsonArray.get(i);
// JSONArray toDescriptionArrays = k3Data.getJSONObject("to_Description").getJSONArray("results");
// for (Object toDescriptionArray : toDescriptionArrays) {
// com.alibaba.fastjson.JSONObject toDescriptionArray1 = (com.alibaba.fastjson.JSONObject) toDescriptionArray;
// String product = (String) toDescriptionArray1.get("Product");
// String productDescription = (String) toDescriptionArray1.get("ProductDescription");
// }
// }
// System.out.println(jsonObject);
}java
扩展另一种方法
1、导包
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
2、工具类
package com.zhuicat.pojo;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
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;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @ClassName HttpUtils
* @Description 请求工具
* @Author msx
* @Date 2021-08-26 17:40
* @Version 1.0
*/
public class HttpUtils {
/**
* @param url-[请求地址] headMap-[请求头参数] paramMap-[请求参数]
* @return String 返回结果
* @Description get请求,参数k-v形式
* @Author msx
* @Date 2021-08-26 17:41
*/
public static String doGet(String url, Map<String, String> headMap, Map<String, String> paramMap) {
System.out.println(" = = 请求地址 = = > > > > > > " + url);
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
CloseableHttpResponse response = null;
try {
//创建uri
URIBuilder builder = new URIBuilder(url);
if (paramMap != null && !paramMap.isEmpty()) {
Set<Map.Entry<String, String>> entrySet = paramMap.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
builder.addParameter(entry.getKey(), entry.getValue());
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
//添加请求头
if (headMap != null && !headMap.isEmpty()) {
Set<Map.Entry<String, String>> entries = headMap.entrySet();
System.out.println(" = = 请求头 = = > > > > > > ");
for (Map.Entry<String, String> e : entries) {
System.out.println(e.getKey() + ":" + e.getValue());
httpGet.addHeader(e.getKey(), e.getValue());
}
}
// 执行请求
response = httpClient.execute(httpGet);
// 判断返回状态是否为200
/*if (response.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
}*/
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, "utf-8");
System.out.println(" = = 请求返回 = = > > > > > > " + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeResource(response, httpClient);
}
return result;
}
/**
* @param url-[请求地址] headMap-[请求头参数] paramMap-[请求参数]
* @return String 返回结果
* @Description post请求,参数k-v形式
* @Author msx
* @Date 2021-08-29 21:13
*/
public static String doPost(String url, Map<String, String> headMap, Map<String, String> paramMap) {
System.out.println(" = = 请求地址 = = > > > > > > " + url);
System.out.println(" = = 请求参数 = = > > > > > > " + paramMap);
//创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = "";
try {
//创建uri
URIBuilder builder = new URIBuilder(url);
if (paramMap != null && !paramMap.isEmpty()) {
Set<Map.Entry<String, String>> entrySet = paramMap.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
builder.addParameter(entry.getKey(), entry.getValue());
}
}
URI uri = builder.build();
//创建http请求
HttpPost httpPost = new HttpPost(uri);
//添加请求头
if (headMap != null && !headMap.isEmpty()) {
System.out.println(" = = 请求头 = = > > > > > > ");
Set<Map.Entry<String, String>> entries = headMap.entrySet();
for (Map.Entry<String, String> entry : entries) {
System.out.println(entry.getKey() + ":" + entry.getValue());
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
// 执行请求
response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(" = = 请求返回 = = > > > > > > " + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭资源
closeResource(response, httpClient);
}
return result;
}
/**
* @param url-[请求地址] headMap-[请求头参数] paramMap-[请求参数]
* @return String 返回结果
* @Description post请求,请求体为JSON格式
* @Author msx
* @Date 2021-08-27 16:31
*/
public static String doPost(String url, Map<String, String> header, String jsonParams) {
System.out.println(" = = 请求地址 = = > > > > > > " + url);
System.out.println(" = = 请求参数 = = > > > > > > " + jsonParams);
//创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = "";
try {
//创建http请求
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
//创建请求内容
StringEntity entity = new StringEntity(jsonParams, "utf-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
// 设置请求头
if (null != header && !header.isEmpty()) {
System.out.println(" = = 请求头 = = > > > > > > ");
Set<Map.Entry<String, String>> entries = header.entrySet();
for (Map.Entry<String, String> e : entries) {
System.out.println(e.getKey() + ":" + e.getValue());
httpPost.setHeader(e.getKey(), e.getValue());
}
}
response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(" = = 请求返回 = = > > > > > > " + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭资源
closeResource(response, httpClient);
}
return result;
}
/**
* @Description 关闭资源
* @Author msx
* @Date 2021/9/8 10:44
*/
private static void closeResource(Closeable... resources) {
System.out.println("> > > > > > > > > > 关闭流资源 > > > > > > > > > >");
try {
for (Closeable resource : resources) {
if (resource != null) {
resource.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}