新建maven工程,在pom.xml中导入httpclient与fastjson包,httpclient用来请求,fastjson进行参数转换与处理数据。
主方法
SHA1算法加密
POST 方法
利用 HttpClientBuilder创建连接对象
public static String postMethod(String url, JSONObject json){
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
StringEntity s = new StringEntity(json.toString());
s.setContentEncoding("UTF-8");
//发送json数据需要设置contentType
s.setContentType("application/x-www-form-urlencoded");
post.setEntity(s); //设置请求参数
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode){
//返回String
String res = EntityUtils.toString(response.getEntity());
System.out.println(res);
return res;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
GET方法
利用 HttpClientBuilder创建连接对象
public static String getMethod(String url){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(url);
try{
//这里可以设置请求参数,token等
get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
HttpResponse response = httpClient.execute(get);//执行获取响应
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){//根据状态码处理
//返回字符串
String res = EntityUtils.toString(response.getEntity());
System.out.println(res);
return res;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
参数处理与解析数据
获得的响应参数可以使用json‘进行分析,[ ]为数组,{ }为对象,利用 JSONObject.parseObject(String text)将字符串转为json对象,调用getJSONArray(key)获取json数组JSONArray,getString(key)获取对应的值,getJSONObject()获取json对象。可以根据json结构层层解析,获取需要的数据。
新建json对象,调用put方法可以赋值,之后作为请求参数设置。
本文介绍了如何在Maven项目中使用HttpClient进行HTTP请求,包括POST和GET方法,并结合Fastjson处理JSON数据,重点展示了SHA1加密和参数转换过程。


2135

被折叠的 条评论
为什么被折叠?



