场景描述:
在与第三方进行对接时,其中要求设置请求头等信息,通过验证后来获取数据,所以以此来记录一下这个流程,希望对大家有所帮助。代码如下:
public JSONObject add(String url) throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url); //http的get请求方式
httpGet.addHeader("Content-Type","application/json"); //后面还可以设置其他请求头信息
httpGet.addHeader("名称","值");
JSONObject jsonObject = null;
CloseableHttpResponse response= null;
try {
response = client.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ //相当于判断请求返回的编码是否为200
HttpEntity entity = response.getEntity(); //获取数据
String result = EntityUtils.toString(entity); //将返回的结果转换为字符串
jsonObject = JSONObject.parseObject(result); //字符串转为json格式
}
}catch (Exception e){
throw new RuntimeException(e);
}finally {
if (response!=null){
response.close(); //关闭response
}
if (client!=null){
client.close(); //关闭client
}
}
return jsonObject; //返回json对象
}