一、http请求工具类
package com.azxc.rapid.modules.dock.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.util.*;
import java.util.Map.Entry;
/**
* 在java中处理http请求.
*/
@Slf4j
public class HttpUtils {
private static HttpUtils instance;
public static HttpUtils getInstance() {
if (instance == null) {
instance = new HttpUtils();
}
return instance;
}
private HttpUtils() {
}
/**
* get请求
*
* @param url
* @param params
* @return
*/
public String get(String url, Map<String, String> params) {
// 实例化httpclient
DefaultHttpClient httpclient = (DefaultHttpClient) getHttpClient();
StringBuffer sb = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
}
if (sb.length() > 0) {
String str = String.valueOf(sb);
str = str.substring(0, str.length() - 1);
if (url != null && url.contains("?")) {
url = url + "&" + str.toString();
} else {
url = url + "?" + str.toString();
}
}
System.out.println("get url=" + url);
// 实例化get方法
HttpGet httpget = new HttpGet(url);
// 请求结果
CloseableHttpResponse response = null;
String content = "";
try {
// 执行get方法
response = httpclient.execute(httpget);
log.info("get响应:" + response);
// log.info("get响应内容:"+EntityUtils.toString(response.getEntity(), "utf-8"));
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), "utf-8");
log.info("get响应结果:" + content);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
log.info("异常:" + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
/**
* 处理post请求.
*
* @param url 请求路径
* @param params 参数
* @return json
*/
public String post(String url, Map<String, String> params) {
// 实例化httpClient
DefaultHttpClient httpclient = (DefaultHttpClient) getHttpClient();
// 实例化post方法
HttpPost httpPost = new HttpPost(url);
// 处理参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (params != null) {
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
}
// 结果
CloseableHttpResponse response = null;
String content = "";
try {
// 提交的参数
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
// 将参数给post方法
httpPost.setEntity(uefEntity);
// 执行post方法
response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), "utf-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
@SuppressWarnings("deprecation")
public static HttpClient getHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = DefaultSSLSocketFactory.getSocketFactory();
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
/**
* params参数 body
* 请求头application/x-www-form-urlencoded
*/
public static String postString(String url, String params) throws Exception {
Map header = new HashMap();
header.put("content-type", "application/x-www-form-urlencoded");
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
log.info("POST请求url:" + url);
for (Iterator iter = header.keySet().iterator(); iter.hasNext(); ) {
String key = String.valueOf(iter.next());
String value = String.valueOf(header.get(key));
httpPost.setHeader(key, value);
}
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(20000)
.setSocketTimeout(20000).setConnectTimeout(20000).build();
httpPost.setConfig(requestConfig);
//设置参数
log.info("POST请求参数:" + params);
StringEntity entity = new StringEntity(params, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
return jsonString;
} else {
log.error("请求返回:" + state + "(" + url + ")");
}
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 参数body
* 请求头application/json
*/
public String postString(String url, String json, String token) {
String returnValue = null;
DefaultHttpClient httpClient = (DefaultHttpClient) getHttpClient();
CloseableHttpResponse httpResonse = null;
System.out.println(url);
System.out.println(json);
try {
HttpPost httpPost = new HttpPost(url);
StringEntity requestEntity = new StringEntity(json, "utf-8");
requestEntity.setContentEncoding("UTF-8");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept-type", MediaType.APPLICATION_JSON.toString());
httpPost.setHeader("Authorization", "Bearer " + token);
httpPost.setEntity(requestEntity);
httpResonse = httpClient.execute(httpPost);
if (httpResonse.getStatusLine().getStatusCode() == 200) {
returnValue = EntityUtils.toString(httpResonse.getEntity(), "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.close();
}
// try {
// String postURL = "http://*.*.*.*:8080/cjs/ad";
// PostMethod postMethod = null;
// postMethod = new PostMethod(postURL);
// //添加请求头数据
// postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// //参数设置,需要注意的就是里边不能传NULL,要传空字符串
// NameValuePair[] data = {
// new NameValuePair("_ArgStr1", "*"),
// new NameValuePair("_ArgStr2", "*")
// };
// NameValuePair a = new NameValuePair("a", "a");
// postMethod.setRequestBody(data);
//
// org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
// int response = httpClient.executeMethod(postMethod); // 执行POST方法
// String result = postMethod.getResponseBodyAsString();
// System.out.println(response);
// System.out.println(result);
// } catch (Exception e) {
// // logger.info("请求异常"+e.getMessage(),e);
// throw new RuntimeException(e.getMessage());
// }
return returnValue;
}
/**
* post请求 请求头 application/x-www-form-urlencoded
*
* @param strUrl
* @param content
* @return
*/
public static String doPost(String strUrl, String content) {
String result = "";
try {
URL url = new URL(strUrl);
//通过调用url.openConnection()来获得一个新的URLConnection对象,并且将其结果强制转换为HttpURLConnection.
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
//设置连接的超时值为30000毫秒,超时将抛出SocketTimeoutException异常
urlConnection.setConnectTimeout(30000);
//设置读取的超时值为30000毫秒,超时将抛出SocketTimeoutException异常
urlConnection.setReadTimeout(30000);
//将url连接用于输出,这样才能使用getOutputStream()。getOutputStream()返回的输出流用于传输数据
urlConnection.setDoOutput(true);
//设置通用请求属性为默认浏览器编码类型
urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
//getOutputStream()返回的输出流,用于写入参数数据。
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(content.getBytes());
outputStream.flush();
outputStream.close();
//此时将调用接口方法。getInputStream()返回的输入流可以读取返回的数据。
InputStream inputStream = urlConnection.getInputStream();
byte[] data = new byte[1024];
StringBuilder sb = new StringBuilder();
//inputStream每次就会将读取1024个byte到data中,当inputSteam中没有数据时,inputStream.read(data)值为-1
while (inputStream.read(data) != -1) {
String s = new String(data, Charset.forName("utf-8"));
sb.append(s);
}
result = sb.toString();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 发送delete请求
*
* @param url
* @param token
* @param jsonStr
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String deleteString(String url, String jsonStr, String token) throws IOException {
String returnValue = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
StringEntity requestEntity = new StringEntity(jsonStr, "utf-8");
requestEntity.setContentEncoding("UTF-8");
httpDelete.setHeader("Content-type", "application/json");
httpDelete.setHeader("Accept-type", MediaType.APPLICATION_JSON.toString());
httpDelete.setHeader("Authorization", "Bearer " + token);
// httpDelete.setEntity(requestEntity);
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpDelete);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
returnValue = EntityUtils.toString(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.close();
}
return returnValue;
}
}
二、实现get请求
Map<String, String> userParams = new HashMap<>();
userParams.put("access_token", "token信息");
userParams.put("client_id","客户端ID信息");
userParams.put("uid","用户ID");
String userResult = HttpUtils.getInstance().get("url地址", userParams);
log.info("3 用户信息接口返回结果:" + userResult);
三、实现post请求
String tokenParams = "client_id=" + 参数值1 + "&client_secret=" + 参数值2 + "&code=" + 参数值3+ "&grant_type=参数值4";
String tokenResult = HttpUtils.postString(url网址, tokenParams);
log.info("post请求接口返回结果:" + tokenResult);