public static void main(String[] args) throws IOException {
//1.打开浏览器
CloseableHttpClient httpClient = HttpClients.createDefault();
//2.声明get请求
HttpGet httpGet = new HttpGet("http://www.baidu.com/");
//3.发送请求
CloseableHttpResponse response = httpClient.execute(httpGet);
//4.判断状态码
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity = response.getEntity();
//通过EntityUtils工具类转成字符串
String string = EntityUtils.toString(entity, "utf-8");
System.out.println(string);
}
//5.关闭资源
response.close();
httpClient.close();
}
public String send(String postUrl,String json,String sign,String token) {
String params = JSON.toJSONString(json);
System.out.println(params);
String url = postUrl;
HttpClient httpClient = null;
HttpPost postMethod = null;
HttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
postMethod = new HttpPost(url);//传入URL地址
//设置请求头
postMethod.addHeader("Content-type", "application/json");
postMethod.addHeader("sign", sign);//设置请求头
postMethod.addHeader("token",token);
//传入请求参数
postMethod.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
response = httpClient.execute(postMethod);//获取响应
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("HTTP Status Code:" + statusCode);
if (statusCode != HttpStatus.SC_OK) {
System.out.println("HTTP请求未成功!HTTP Status Code:" + response.getStatusLine());
}
HttpEntity httpEntity = response.getEntity();
String reponseContent = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);//释放资源
System.out.println("响应内容:" + reponseContent);
return reponseContent;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}