第一种:通过Apache封装好的CloseableHttpClient
package com.chao.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* 通过Apache封装好的CloseableHttpClient
* @author zhangc
* @date 2023/4/26 9:54
*/
public class CloseableHttpClientUtil {
private static String tokenString = "";
private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED";
private static CloseableHttpClient httpClient = null;
/**
* 以get方式调用第三方接口
* @param url
* @return
*/
public static String doGet(String url, String token){
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(url);
try {
if (tokenString != null && !tokenString.equals("")){
tokenString = getToken();
}
//api_gateway_auth_token自定义header头,用于token验证使用
get.addHeader("api_gateway_auth_token", tokenString);
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){
//返回json格式
String res = EntityUtils.toString(response.getEntity());
return res;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 以post方式调用第三方接口
* @param url
* @param json
* @return
*/
public static String doPost(String url, JSONObject json){
try {
if (httpClient == null){
httpClient = HttpClientBuilder.create().build();
}
HttpPost post = new HttpPost(url);
if (tokenString != null && !tokenString.equals("")){
tokenString = getToken();
}
//api_gateway_auth_token自定义header头,用于token验证使用
post.addHeader("api_gateway_auth_token", tokenString);
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);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//返回json格式
String res = EntityUtils.toString(response.getEntity());
return res;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 以post方式调用第三方接口
* @param url
* @param contentType
* @param json
* @return
*/
public static String doPost(String url,String contentType, JSONObject json){
try {
if (httpClient == null){
httpClient = HttpClientBuilder.create().build();
}
HttpPost post = new HttpPost(url);
if (tokenString != null && !tokenString.equals("")){
tokenString = getToken();
}
//api_gateway_auth_token自定义header头,用于token验证使用
post.addHeader("api_gateway_auth_token", tokenString);
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(contentType);
//设置请求参数
post.setEntity(s);
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//返回json格式
String res = EntityUtils.toString(response.getEntity());
return res;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 获取第三方接口的token
*/
public static String getToken(){
String token = "";
JSONObject object = new JSONObject();
object.put("appid", "appid");
object.put("secretkey", "secretkey");
try {
if (httpClient == null){
httpClient = HttpClientBuilder.create().build();
}
HttpPost post = new HttpPost("http://localhost/login");
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(object.toString());
s.setContentEncoding("UTF-8");
//发送json数据需要设置contentType
s.setContentType("application/x-www-form-urlencoded");
//设置请求参数
post.setEntity(s);
HttpResponse response = httpClient.execute(post);
//这里可以把返回的结果按照自定义的返回数据结果,把string转换成自定义类
//ResultTokenBO result = JSONObject.parseObject(response, ResultTokenBO.class);
//把response转为jsonObject
JSONObject result = JSONObject.parseObject(response.toString());
if (result.containsKey("token")){
token = result.getString("token");
}
} catch (Exception e) {
e.printStackTrace();
}
return token;
}
/**
* 测试
*/
public static void test(String telephone){
JSONObject object = new JSONObject();
object.put("telephone", telephone);
try {
//首先获取token
tokenString = getToken();
String response = doPost("http://localhost/searchUrl", object);
//如果返回的结果是list形式的,需要使用JSONObject.parseArray转换
//List<Result> list = JSONObject.parseArray(response, Result.class);
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id","3543532");
jsonObject.put("businessId","1232312");
jsonObject.put("className","ha");
jsonObject.put("methodName","post");
String result = doPost("http://localhost:8081/payment/test","application/json",jsonObject);
System.out.println(result);
}
/**
* 执行一个HTTP POST请求,返回请求响应的HTML
* @param url
* 请求的URL地址
* @return 返回请求响应的HTML
*/
public static void doPost(String url, String name, String pwd, String phone, String content) {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("account", name));
formparams.add(new BasicNameValuePair("passwd", pwd));
formparams.add(new BasicNameValuePair("phone", phone));
formparams.add(new BasicNameValuePair("content", content));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
第二种:通过Apache common封装好的HttpClient
package com.chao.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
/**
* 通过Apache common封装好的HttpClient
* httpClient的get请求方式
* 使用GetMethod来访问一个URL对应的网页实现步骤:
* 1.生成一个HttpClient对象并设置相应的参数;
* 2.生成一个GetMethod对象并设置响应的参数;
* 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
* 4.处理响应状态码;
* 5.若响应正常,处理HTTP响应内容;
* 6.释放连接
* @author zhangc
* @date 2023/4/26 9:43
*/
public class HttpClientUtil {
/**
* @param url
* @param charset
* @return
*/
public static String doGet(String url, String charset){
/**
* 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:" + response);
//读取为InputStream,在网页内容数据量大时候推荐使用
//InputStream response = getMethod.getResponseBodyAsStream();
} catch (HttpException e) {
//发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("请检查输入的URL!");
e.printStackTrace();
} catch (IOException e){
//发生网络异常
System.out.println("发生网络异常!");
}finally {
/**
* 6.释放连接
*/
getMethod.releaseConnection();
}
return response;
}
/**
* post请求
* @param url
* @param json
* @return
*/
public static String doPost(String url,JSONObject json){
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("accept", "*/*");
postMethod.addRequestHeader("connection", "Keep-Alive");
//设置json格式传送
postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
//必须设置下面这个Header
postMethod.addRequestHeader("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");
//添加请求参数
//postMethod.addParameter("param", json.getString("param"));
StringRequestEntity param = new StringRequestEntity(json.toString());
postMethod.setRequestEntity(param);
String res = "";
try {
int code = httpClient.executeMethod(postMethod);
if (code == 200){
byte[] responseBody = postMethod.getResponseBody();
res = new String(responseBody, "UTF-8");
//res = postMethod.getResponseBodyAsString();
System.out.println(res);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
postMethod.releaseConnection();
}
return res;
}
/**
* post请求
* @param url
* @param json
* @return
*/
public static String doPost(String url, Map<String,String> headerMap, JSONObject json){
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("accept", "*/*");
postMethod.addRequestHeader("connection", "Keep-Alive");
//设置json格式传送
postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
//必须设置下面这个Header
postMethod.addRequestHeader("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");
for(Map.Entry<String,String> entry:headerMap.entrySet()){
postMethod.addRequestHeader(entry.getKey(), entry.getValue());
}
//添加请求参数
//postMethod.addParameter("param", json.getString("param"));
StringRequestEntity param = new StringRequestEntity(json.toString());
postMethod.setRequestEntity(param);
String res = "";
try {
int code = httpClient.executeMethod(postMethod);
if (code == 200){
byte[] responseBody = postMethod.getResponseBody();
res = new String(responseBody, "UTF-8");
//res = postMethod.getResponseBodyAsString();
System.out.println(res);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
postMethod.releaseConnection();
}
return res;
}
public void moveZeroes(int[] nums) {
//最优解法
int left =0,right = 0;
while(right<nums.length){
if(nums[right]!=0){
int temp = nums[right];
nums[left] = nums[right];
nums[right] = temp;
left ++;
}
right ++;
}
}
public static void main(String[] args) {
int left,right = 0;
JSONObject jsonObject = new JSONObject();
jsonObject.put("id","3543532");
jsonObject.put("businessId","1232312");
jsonObject.put("className","ha");
jsonObject.put("methodName","post");
String result = HttpClientUtil.doPost("http://localhost:8081/payment/test",jsonObject);
System.out.println(result);
}
}
第三种:jdk 调用第三方接口
package com.chao.utils;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* jdk 调用第三方接口
* @author zhangc
* @date 2023/4/26 9:42
*/
public class HttpClientUtil2 {
/**
* 以post方式调用对方接口方法
* @param pathUrl
* @param data json格式参数
*/
public static String doPost(String pathUrl, String data){
OutputStreamWriter out = null;
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设定请求的方法为"POST",默认是GET
//post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
conn.setRequestMethod("POST");
//设置30秒连接超时
conn.setConnectTimeout(30000);
//设置30秒读取超时
conn.setReadTimeout(30000);
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
conn.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
conn.setDoInput(true);
// Post请求不能使用缓存
conn.setUseCaches(false);
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive"); //维持长链接
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
conn.connect();
/**
* 下面的三句代码,就是调用第三方http接口
*/
//获取URLConnection对象对应的输出流
//此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用上述的connect()也可以)。
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
//发送请求参数即数据
out.write(data);
//flush输出流的缓冲
out.flush();
/**
* 下面的代码相当于,获取调用第三方http接口后返回的结果
*/
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
System.out.println(result);
//关闭流
is.close();
//断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (out != null){
out.close();
}
if (br != null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 以get方式调用对方接口方法
* @param pathUrl
*/
public static String doGet(String pathUrl){
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设定请求的方法为"GET",默认是GET
//post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
conn.setRequestMethod("GET");
//设置30秒连接超时
conn.setConnectTimeout(30000);
//设置30秒读取超时
conn.setReadTimeout(30000);
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
conn.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
conn.setDoInput(true);
// Post请求不能使用缓存(get可以不使用)
conn.setUseCaches(false);
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive"); //维持长链接
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
//连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
conn.connect();
/**
* 下面的代码相当于,获取调用第三方http接口后返回的结果
*/
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
System.out.println(result);
//关闭流
is.close();
//断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (br != null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id","3543532");
jsonObject.put("businessId","1232312");
jsonObject.put("className","ha");
jsonObject.put("methodName","post");
String result = doPost("http://localhost:8081/payment/test",jsonObject.toJSONString());
System.out.println(result);
}
}
第四种:…待续