Java教程:Https(get,post)请求工具类
源码:
HttpClientUtil
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.client.methods.HttpRequestBase;
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.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Java实现Post请求-工具类
*
* @author wfeil211@foxmail.com
* @version 2020-1-2 15:26:41
*/
public class HttpClientUtil {
private static Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class);
private static HttpClientUtil instance;
protected Charset charset;
private HttpClientUtil() {
}
public static HttpClientUtil getInstance() {
return getInstance(Charset.defaultCharset());
}
public static HttpClientUtil getInstance(Charset charset) {
if (instance == null) {
instance = new HttpClientUtil();
}
instance.setCharset(charset);
return instance;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
/**
* post请求
*/
public String doPost(String url, Map<String, Object> params) throws Exception {
return doPost(url, params, "");
}
public String postJson(String url, JSONObject json) throws Exception {
return postJson(json, url);
}
public String sendPost(String curl, String param) {
String result = "";// 返回的结果
BufferedReader in = null;// 读取响应输入流
LOG.debug(" params: " + param);
try {
//创建连接
URL url = new URL(curl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true); //是否打开outputStream 相对于程序,即我们向远程服务器写入数据,默认为false,不打开
connection.setDoInput(true); //输入流,获取到返回的响应内容, 默认为true,所以get请求时可以不设置这个连接信息
connection.setRequestMethod("POST"); //发送请求的方式
connection.setUseCaches(false); //不使用缓存
connection.setInstanceFollowRedirects(true); //重定向,一般浏览器才需要
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8"); //设置服务器解析数据的方式
connection.connect();
//POST请求
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
out.write(param);
out.flush();
out.close();
//读取响应
// 定义BufferedReader输入流来读取URL的响应,并设置编码方式
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Http请求方法内部问题");
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public String doPost(String url,Map<String,Object> map,String charset){
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new SSLClient();
httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
private String postJson(JSONObject json, String URL) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result = "";
try {
StringEntity s = new StringEntity(json.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(s);
// 发送请求
HttpResponse httpResponse = client.execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
result = strber.toString();
System.out.println(result);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("请求服务器成功,做相应处理");
} else {
System.out.println("请求服务端失败");
}
} catch (Exception e) {
System.out.println("请求异常");
throw new RuntimeException(e);
}
return result;
}
private String doPost(String url, Map<String, Object> params, Map<String, String> header) throws Exception {
String body = null;
try {
// Post请求
LOG.debug(" protocol: POST");
LOG.debug(" url: " + url);
HttpPost httpPost = new HttpPost(url.trim());
// 设置参数
LOG.debug(" params: " + JSON.toJSONString(params));
httpPost.setEntity(new UrlEncodedFormEntity(map2NameValuePairList(params), charset));
// 设置Header
if (header != null && !header.isEmpty()) {
LOG.debug(" header: " + JSON.toJSONString(header));
for (Iterator<Entry<String, String>> it = header.entrySet().iterator(); it.hasNext(); ) {
Entry<String, String> entry = (Entry<String, String>) it.next();
httpPost.setHeader(new BasicHeader(entry.getKey(), entry.getValue()));
}
}
// 发送请求,获取返回数据
body = execute(httpPost);
} catch (Exception e) {
throw e;
}
LOG.debug(" result: " + body);
return body;
}
private String execute(HttpRequestBase requestBase) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
String body = null;
try {
CloseableHttpResponse response = httpclient.execute(requestBase);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, charset.toString());
}
EntityUtils.consume(entity);
} catch (Exception e) {
throw e;
}finally {
response.close();
}
} catch (Exception e) {
throw e;
} finally {
httpclient.close();
}
return body;
}
private List<NameValuePair> map2NameValuePairList(Map<String, Object> params) {
if (params != null && !params.isEmpty()) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator<String> it = params.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
if(params.get(key) != null) {
String value = String.valueOf(params.get(key));
list.add(new BasicNameValuePair(key, value));
}
}
return list;
}
return null;
}
}
SSLClient
import org.apache.http.conn.ClientConnectionManager;
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.impl.client.DefaultHttpClient;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* Java实现Post请求-工具类
*
* @author wfeil211@foxmail.com
* @version 2020-1-2 15:26:41
*/
//用于进行Https请求的HttpClient
public class SSLClient extends DefaultHttpClient{
public SSLClient() throws Exception{
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
版权声明:本文为wfeil211原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。