在项目中,我们需要对url进行解析处理,但是我们但是不知道url是post还是get请求,有时候呢,大量请求的时候有post也有get请求,但是我们又希望能稳定的得到书记,那么我们该怎么处理呢?
话不多说,先上示例代码:
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请求
- @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请求
- @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设置封装好的请求参数
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 响应
* @param httpClient 客户端实例
*/
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();
}
}
}));
}
/**
* 判断请求的方法是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;
}
}
我引入的包,只作单纯的请求,只要最后2个包就可以了:
<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>
网友评论