httpclient,URL
网上介绍java,httpclients使用比较多,大多是比较老板本,或是感觉不完善,或是不安全的,于是借鉴并整理了简单的工具类,好,先给出官方httpclient api,代码如下:
import org.apache.http.HttpEntity;
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.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by on 2017/2/16.
* httpclien version 4.4.1
*/
public class HttpClientUtil {
private static PoolingHttpClientConnectionManager cm = null;
private static int POOL_MAX_CON = 50;// 整个连接池最大连接数
private static int MAX_PERROUTE = 5;// 每路由最大连接数,默认值是2
private static String CHARSET = "UTF-8";
private HttpClientUtil() {
}
/**
* 初始化连接池
*/
private static void init() {
if (cm == null) {
synchronized (HttpClientUtil.class) {
if (cm == null) {
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(POOL_MAX_CON);
cm.setDefaultMaxPerRoute(MAX_PERROUTE);
}
}
}
}
/**
* get请求
*/
public static String get(String url) {
HttpGet httpGet = new HttpGet(url);
return handleResult(httpGet);
}
/**
* 带有参数get请求
*/
public static String getByParameter(String url, Map<String, Object> params) throws URISyntaxException {
URIBuilder ub = new URIBuilder().setPath(url).setParameters(wrapParameter(params));
HttpGet httpGet = new HttpGet(ub.build());
return handleResult(httpGet);
}
/**
* post请求
*/
public static String post(String url) {
HttpPost httpPost = new HttpPost(url);
return handleResult(httpPost);
}
/**
* 带有参数post请求
*/
public static String postByParameter(String url, Map<String, Object> params) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(wrapParameter(params), CHARSET));
return handleResult(httpPost);
}
/**
* 处理请求参数
*/
private static ArrayList<NameValuePair> wrapParameter(Map<String, Object> params) {
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
if (params != null) {
for (Map.Entry<String, Object> param : params.entrySet()) {
pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
}
}
return pairs;
}
/**
* 获取httpclient
*/
private static CloseableHttpClient getHttpClient() {
init();
// HttpClientBuilder hcb = HttpClients.custom();
// HttpClientBuilder hcbui = HttpClientBuilder.create();
return HttpClients.custom().setConnectionManager(cm).build();
}
/**
* 处理请求结果,返回json字符串
*/
private static String handleResult(HttpRequestBase request) {
String result = null;
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, CHARSET);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static void main(String[] args) throws IOException, URISyntaxException {
Map<String, Object> map = new HashMap<String, Object>();
String url = "http://172.16.50.54/machine/machineApi";
map.put("method", "findOrderByMobileAndCode");
map.put("mobile", "18600409520");
map.put("checkCode", "123456");
String str = getByParameter(url, map);
System.out.println(str);
}
}
// 附带校验URL有效工具类package common;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by on 2017/2/16.
*/
public class URLValidUtil {
/**
* 校验url是否可用
*
* @param url 请求URL
* @param reTryCount 连接次数
*/
public boolean validUrl(String url, Integer reTryCount) {
URL Url = null;
HttpURLConnection con = null;
int counts = 0;
boolean result = false;
if (url == null || url.length() <= 0)
return result;
if (reTryCount == null || reTryCount <= 0)
reTryCount = 1;
try {
Url = new URL(url);
while (counts < reTryCount) {
con = (HttpURLConnection) Url.openConnection();
int code = con.getResponseCode();
if (code == 200) {
result = true;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null)
con.disconnect();
if (Url != null)
Url = null;
}
return result;
}
} 相关推荐
84487600 2020-08-16
似水流年梦 2020-08-09
knightwatch 2020-07-26
fengchao000 2020-06-16
标题无所谓 2020-06-14
sicceer 2020-06-12
yanghui0 2020-06-09
yanghui0 2020-06-09
创建一个 HttpClient 实例,这个实例需要调用 Dispose 方法释放资源,这里使用了 using 语句。接着调用 GetAsync,给它传递要调用的方法的地址,向服务器发送 Get 请求。
wanghongsha 2020-06-04
jiaguoquan00 2020-05-26
zhaolisha 2020-05-16
wanghongsha 2020-05-05
wanghongsha 2020-04-14
knightwatch 2020-04-11
hygbuaa 2020-03-27
zergxixi 2020-03-24