在項(xiàng)目中,我們需要對(duì)url進(jìn)行解析處理垃帅,但是我們但是不知道url是post還是get請(qǐng)求延届,有時(shí)候呢,大量請(qǐng)求的時(shí)候有post也有g(shù)et請(qǐng)求贸诚,但是我們又希望能穩(wěn)定的得到書(shū)記方庭,那么我們?cè)撛趺刺幚砟兀?/p>
話不多說(shuō)厕吉,先上示例代碼:
package com.ky.common;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.HttpGet;
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 java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.Map.Entry;
/**
@Author: xwj
@Date: 2019/3/5 0005 16:13
-
@Version 1.0
*/
public class BaseFunction {/**
- get請(qǐng)求
- @param url url地址
- @return string
*/
private static String getRequest(String url) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
.setConnectionRequestTimeout(60000)
.setSocketTimeout(80000)
.build();
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
shutdown(response, httpClient);
}
return result;
}
/**
- post請(qǐng)求
- @param url url地址
- @return string
*/
private static String postRequest(String url) {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("Accept-Charset", "utf-8");
paramMap.put("Content-Type", "application/x-www-form-urlencoded");
paramMap.put("Content-Length", "");
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
String result = "";
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
.setConnectionRequestTimeout(35000)
.setSocketTimeout(60000)
.build();
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
if (paramMap.size() > 0) {
List<NameValuePair> nvps = new ArrayList<>();
Set<Entry<String, Object>> entrySet = paramMap.entrySet();
for (Entry<String, Object> mapEntry : entrySet) {
nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
}
// 為httpPost設(shè)置封裝好的請(qǐng)求參數(shù)
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
try {
httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
result = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
shutdown(httpResponse, httpClient);
}
return result;
}
/**
* 釋放連接
*
* @param response 響應(yīng)
* @param httpClient 客戶端實(shí)例
*/
private static void shutdown(final CloseableHttpResponse response, final CloseableHttpClient httpClient) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}));
}
/**
* 判斷請(qǐng)求的方法是get還是post
*
* @param url
* @return
*/
public static String parseUrl(String url) {
HttpURLConnection httpURLConnection = null;
String method = "";
String post = "POST";
String get = "GET";
String data = "";
try {
URL localUrl = new URL(url);
URLConnection connection = null;
connection = localUrl.openConnection();
httpURLConnection = (HttpURLConnection) connection;
method = httpURLConnection.getRequestMethod();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
if (method.equalsIgnoreCase(post)) {
data = postRequest(url);
} else if (method.equalsIgnoreCase(get)) {
data = getRequest(url);
} else {
try {
throw new Exception(String.format("HTTP Request is not success, please sure the url:%s is correct", url));
} catch (Exception e) {
e.printStackTrace();
}
}
return data;
}
}
我引入的包,只作單純的請(qǐng)求械念,只要最后2個(gè)包就可以了:
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.1</version>
</dependency>