GET请求
public static String doGet(String url, String charset){
System.out.println("请求的接口:"+url);
/**
* 1.生成HttpClient对象并设置参数
*/
HttpClient httpClient = new HttpClient();
//设置Http连接超时为5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
/**
* 2.生成GetMethod对象并设置参数
*/
GetMethod getMethod = new GetMethod(url);
//设置get请求超时为5秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
//设置请求重试处理,用的是默认的重试处理:请求三次
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
/**
* 3.执行HTTP GET 请求
*/
try {
int statusCode = httpClient.executeMethod(getMethod);
/**
* 4.判断访问的状态码
*/
if (statusCode != HttpStatus.SC_OK){
System.err.println("请求出错:" + getMethod.getStatusLine());
}
/**
* 5.处理HTTP响应内容
*/
//HTTP响应头部信息,这里简单打印
Header[] headers = getMethod.getResponseHeaders();
/* for (Header h: headers){
System.out.println(h.getName() + "---------------" + h.getValue());
}*/
//读取HTTP响应内容,这里简单打印网页内容
//读取为字节数组
byte[] responseBody = getMethod.getResponseBody();
response = new String(responseBody, charset);
System.out.println("接口返回数据为:" + response);
//读取为InputStream,在网页内容数据量大时候推荐使用
//InputStream response = getMethod.getResponseBodyAsStream();
return response;
} catch (HttpException e) {
//发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("请检查输入的URL!");
e.printStackTrace();
return "调用GET请求失败";
} catch (IOException e){
//发生网络异常
System.out.println("发生网络异常!");
e.printStackTrace();
return "调用GET请求失败";
}finally {
/**
* 6.释放连接
*/
getMethod.releaseConnection();
}
}
//get请求示例
String result = HttpClientToInterface.doGet("http://127.0.0.1:8085/xxxx/xxxx?yy=yyyyyy&zz=zzzzzzz","UTF-8");
POST请求
public static String doPost(String url, String charset){
System.out.println("请求的接口:"+url);
/**
* 1.生成HttpClient对象并设置参数
*/
HttpClient httpClient = new HttpClient();
//设置Http连接超时为5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
/**
* 2.生成PostMethod对象并设置参数
*/
PostMethod postMethod = new PostMethod(url);
//设置post请求超时为5秒
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
//设置请求重试处理,用的是默认的重试处理:请求三次
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
/**
* 3.执行HTTP POST 请求
*/
try {
int statusCode = httpClient.executeMethod(postMethod);
/**
* 4.判断访问的状态码
*/
if (statusCode != HttpStatus.SC_OK){
System.err.println("请求出错:" + postMethod.getStatusLine());
}
/**
* 5.处理HTTP响应内容
*/
//HTTP响应头部信息,这里简单打印
Header[] headers = postMethod.getResponseHeaders();
/* for (Header h: headers){
System.out.println(h.getName() + "---------------" + h.getValue());
}*/
//读取HTTP响应内容,这里简单打印网页内容
//读取为字节数组
byte[] responseBody = postMethod.getResponseBody();
response = new String(responseBody, charset);
System.out.println("接口返回数据为:" + response);
//读取为InputStream,在网页内容数据量大时候推荐使用
//InputStream response = getMethod.getResponseBodyAsStream();
return response;
} catch (HttpException e) {
//发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("请检查输入的URL!");
e.printStackTrace();
return "调用POST请求失败";
} catch (IOException e){
//发生网络异常
System.out.println("发生网络异常!");
e.printStackTrace();
return "调用POST请求失败";
}finally {
/**
* 6.释放连接
*/
postMethod.releaseConnection();
}
}
//post请求示例
String result = HttpClientToInterface.doPost("http://127.0.0.1:8085/xxxx/xxxx?yy=yyyyyy&zz=zzzzzzz","UTF-8");
POST请求(JSON传参)
public static String doPost(String url, JSONObject json){
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
// 首先Header部分需要设定字符集为:uft-8
post.addHeader("Content-Type", "application/json;charset=utf-8");
// 此处也需要设定
post.setHeader("Accept", "*/*");
post.setHeader("Accept-Encoding", "gzip, deflate, br");
// post.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
post.setHeader("Connection", "keep-alive");
post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36");
post.setEntity(new StringEntity(json.toString(), Charset.forName("UTF-8"))); //设置请求参数
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;
}else{
return "调用POST请求失败";
}
} catch (Exception e) {
e.printStackTrace();
return "调用POST请求失败";
}
}
//post请求示例-josn传参
Map<String, Object> map = new HashMap<>();
map.put("xxxx", "xxxxxx");
map.put("xxxxx", "xxxxxx");
JSONObject json = new JSONObject(map);
//以post形式请求接口
String result = HttpClientToInterface.doPost("http://127.0.0.1:8085/xxxx/xxxxx/", json);
JSONObject jsonObject = JSONObject.parseObject(result);
String data = jsonObject.get("data").toString();
PUT请求(传TOKEN)
public static String doPut(String url,String token){
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPut httpPut = new HttpPut(url);
//设置编码 , 设置token参数
httpPut.addHeader("Authentication", token);
// 首先Header部分需要设定字符集为:uft-8
httpPut.addHeader("Content-Type", "application/json;charset=utf-8");
// 此处也需要设定
httpPut.setHeader("Accept", "*/*");
httpPut.setHeader("Accept-Encoding", "gzip, deflate, br");
// post.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
httpPut.setHeader("Connection", "keep-alive");
httpPut.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36");
//设置请求参数
System.out.println("Executing request " + httpPut.getRequestLine());
// Create a custom response handler
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpPut, responseHandler);
System.out.println("接口返回数据为:"+responseBody);
return responseBody;
} catch (IOException e) {
e.printStackTrace();
return "调用PUT请求失败";
}
}
//put请求示例
String result = HttpClientToInterface.doPut("http://127.0.0.1:8085/xxxx/xxxxx", token);