在开发项目的过程中经常需要和第三方进行接口对接,这个时候需要调用第三方的接口,为了提高开发效率,我们可以专门封装一个工具类用来调用第三方接口。
HttpUtil
package com.hnxf.video.hunanxfv.util;
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.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HttpUtil {
public static List<NameValuePair> convertMapToPair(Map<String, String> params) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
return pairs;
}
public static String post(String url, Map<String, String> param) {
String result = null;
CloseableHttpResponse httpResponse = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(convertMapToPair(param), "utf-8"));
httpResponse = httpClient.execute(httpPost);
result = EntityUtils.toString(httpResponse.getEntity());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (httpResponse != null) {
httpResponse.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String get(String url, Map<String, Object> param) {
String result = null;
CloseableHttpResponse httpResponse = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(convertMapToPairs(param), "utf-8"));
httpResponse = httpClient.execute(httpPost);
result = EntityUtils.toString(httpResponse.getEntity());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (httpResponse != null) {
httpResponse.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static List<NameValuePair> convertMapToPairs(Map<String, Object> params) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue()));
}
return pairs;
}
}