目录
二、使用HttpsURLConnection发送https请求
三、使用java自带的RestTemplate发送http、https请求
一、使用URLConnection发送http请求
(注意util中最好使用连接池):
1、get请求
get请求只有一种,即参数以&拼接在url后面:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpRequestUtil {
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
}
2、post请求
参数有两种形式,普通参数和对象参数
2.1、(缺省)@RequestParam注解的
和get请求一样把参数放到url后面以&拼接;
2.2、@RequestBody注解的
参数需要放在body中以对象的形式传输,其中调用方式又有多种,常见的有
(1)JSON
(2)form-data
public static String postWithHeader(String url, Map<String, String> header, String body) {
String result = "";
BufferedReader in = null;
PrintWriter out = null;
try {
// 设置 url
URL realUrl = new URL(url);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
// 设置 header
for (String key : header.keySet()) {
connection.setRequestProperty(key, header.get(key));
}
// 设置请求 body
connection.setDoOutput(true);
connection.setDoInput(true);
out = new PrintWriter(connection.getOutputStream());
// 保存body
out.print(body);
// 发送body
out.flush();
// 获取响应body
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
return null;
}
return result;
}
例1:普通参数
public class User implements Serializable {
private String name;
private Integer age;
//省略get和set方法
}
接口:
@PostMapping("/test")
public String getUser(User user, String remark, HttpServletRequest request){
String token = request.getHeader("token");
return "token="+token+";name:"+user.getName()+";age:"+user.getAge()+";remark:"+remark;
}
这是普通的请求,参数拼接在url后面即可:
public class A {
public static void main (String args[]){
String requetUrl = "http://localhost:9999/test";
String param = "name=测试&age=5&remark=gggg";
String url = requetUrl+"?"+param;
Map<String, String> header = new HashMap<>();
header.put("token","123456");
String res = HttpRequestUtil.postWithHeader(url,header,null);
System.out.println(res);
}
}
输出:token=123456;name:测试;age:5;remark:gggg
改用body方式则获取不到参数:
public class A {
public static void main (String args[]){
String requetUrl = "http://localhost:9999/test";
Map<String, String> header = new HashMap<>();
header.put("token","123456");
/* String param = "name=测试&age=5&remark=gggg";
String url = requetUrl+"?"+param;
String res = HttpRequestUtil.postWithHeader(url,header,null);*/
User user = new User();
user.setName("测试");
user.setAge(5);
String param = "remar=gggg";
String url = requetUrl+"?"+param;
String body = JSON.toJSONString(user);
String res = HttpRequestUtil.postWithHeader(url,header,body);
System.out.println(res);
}
}
token=123456;name:null;age:null;remark:null
例2:@RequestBody接口,把User对象加个@RequestBody注解:
@PostMapping("/test")
public String getUser(@RequestBody User user, String remark, HttpServletRequest request){
String token = request.getHeader("token");
return "token="+token+";name:"+user.getName()+";age:"+user.getAge()+";remark:"+remark;
}
public class A {
public static void main (String args[]){
String requetUrl = "http://localhost:9999/test";
Map<String, String> header = new HashMap<>();
header.put("token","123456");
/* String param = "name=测试&age=5&remark=gggg";
String url = requetUrl+"?"+param;
String res = HttpRequestUtil.postWithHeader(url,header,null);*/
User user = new User();
user.setName("测试");
user.setAge(5);
String param = "remark=gggg";
String url = requetUrl+"?"+param;
String body = JSON.toJSONString(user);
String res = HttpRequestUtil.postWithHeader(url,header,body);
System.out.println(res);
}
}
返回结果:
token=123456;name:测试;age:5;remark:gggg
改成url后拼接参数则返回null:
public class A {
public static void main (String args[]){
String requetUrl = "http://localhost:9999/test";
Map<String, String> header = new HashMap<>();
header.put("token","123456");
String param = "name=测试&age=5&remark=gggg";
String url = requetUrl+"?"+param;
String res = HttpRequestUtil.postWithHeader(url,header,null);
System.out.println(res);
}
}
3、util工具类封装
一个好的HttpUtil应该具备以下条件
(1)HttpClient连接使用连接池的方式;
(2)支持get、post,支持post请求不同形式的参数。
import org.apache.commons.collections.MapUtils;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.cookie.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.*;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* http请求工具类
*/
@SuppressWarnings("deprecation")
public class HttpUtil {
private static volatile CloseableHttpClient httpclient = null;
private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
private HttpUtil() {}
private static CloseableHttpClient getHttpClientInstance() {
if (httpclient == null) {
synchronized (HttpUtil.class) {
if (httpclient == null) {
CookieSpecProvider csf = new CookieSpecProvider() {
@Override
public CookieSpec create(HttpContext context) {
return new BrowserCompatSpec() {
@Override
public void validate(Cookie cookie, CookieOrigin origin)
throws MalformedCookieException {
// Allow all cookies
}
};
}
};
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).setCookieSpec("easy").build();
httpclient = HttpClients.custom()
.setDefaultCookieSpecRegistry(RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.BEST_MATCH, csf)
.register(CookieSpecs.BROWSER_COMPATIBILITY, csf)
.register("easy", csf).build())
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(new DefaultHttpRequestRetryHandler())
.build();
}
}
}
return httpclient;
}
/**
* 发送HttpGet请求
* @param url
* @return
*/
public static String sendGet(String url) {
String result = null;
HttpGet httpget = new HttpGet(url);
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = getHttpClientInstance();
response = httpclient.execute(httpget);
} catch (IOException e1) {
log.error(e1.getMessage(), e1);
}
try {
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 发送HttpGet请求
* @param url
* @return
*/
public static String sendGet(String url, Map<String,String> headerMap) {
String result = null;
HttpGet httpget = new HttpGet(url);
//设置请求头
if (MapUtils.isNotEmpty(headerMap)){
for (Map.Entry<String, String> m : headerMap.entrySet()) {
httpget.addHeader(m.getKey(), m.getValue());
}
}
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = getHttpClientInstance();
response = httpclient.execute(httpget);
} catch (IOException e1) {
log.error(e1.getMessage(), e1);
}
try {
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
public static String sendGet(String url, String userName, String password) {
String result = null;
CloseableHttpResponse response = null;
HttpHost target = new HttpHost("xxx.com", 443, "https");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(target.getHostName(), target.getPort()),
new UsernamePasswordCredentials(userName, password));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local
// auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(target, basicAuth);
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
HttpGet httpget = new HttpGet(url);
try {
response = httpclient.execute(target, httpget, localContext);
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 针对jira创建issue的方法
* @param url
* @param basicAuth
* @param postBody
* @return
*/
public static String executePostRequest(String url,String basicAuth ,String postBody) {
httpclient = HttpClients.createDefault();
ResponseHandler<String> handler = new BasicResponseHandler();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Authorization", basicAuth);
httpPost.setHeader("Content-type", "application/json");
StringEntity entity = new StringEntity(postBody, "UTF-8");
entity.setContentType("application/json;charset=UTF-8");
httpPost.setEntity(entity);
String responseBody = null;
HttpResponse response = null;
try {
response = httpclient.execute(httpPost);
responseBody = handler.handleResponse(response);
} catch (IOException e) {
System.out.println(e.getMessage() + " status code: " + response.getStatusLine().getStatusCode());
}
// String ticketNum = null;
// try {
// if (responseBody != null) {
// JSONObject result = JSONObject.parseObject(responseBody);
// ticketNum = result.getString("key");
// }
// } catch (JSONException e) {
// e.printStackTrace();
// }
// System.out.println("Ticket Number: " + ticketNum);
return responseBody;
}
public static String sendPost(String url, String userName, String password,String param) {
String result = null;
CloseableHttpResponse response = null;
HttpHost target = new HttpHost("xxx.com", 443, "https");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(target.getHostName(), target.getPort()),
new UsernamePasswordCredentials(userName, password));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local
// auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(target, basicAuth);
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
StringEntity entityParam = null;
try {
entityParam = new StringEntity(param);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
entityParam.setContentType("application/json");
// entityParam.setContentEncoding("utf-8");
httpPost.setEntity(entityParam);
try {
response = httpclient.execute(target, httpPost, localContext);
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 发送HttpPost请求,参数为map
* @param url
* @param map
* @return
*/
public static String sendPost(String url, Map<String, String> map) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
HttpPost httppost = new HttpPost(url);
httppost.setEntity(entity);
CloseableHttpResponse response = null;
String result = null;
try {
CloseableHttpClient httpclient = getHttpClientInstance();
response = httpclient.execute(httppost);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
HttpEntity entity1 = null;
if (response != null) {
entity1 = response.getEntity();
}
if (entity1 != null) {
result = EntityUtils.toString(entity1);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 发送HttpPost请求,参数为map
* @param url
* @param map
* @return
*/
public static String sendPost(String url, Map<String,String> headerMap, Map<String, String> map) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
HttpPost httppost = new HttpPost(url);
//设置请求头
if (MapUtils.isNotEmpty(headerMap)){
for (Map.Entry<String, String> m : headerMap.entrySet()) {
httppost.addHeader(m.getKey(), m.getValue());
}
}
httppost.setEntity(entity);
CloseableHttpResponse response = null;
String result = null;
try {
CloseableHttpClient httpclient = getHttpClientInstance();
response = httpclient.execute(httppost);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
HttpEntity entity1 = null;
if (response != null) {
entity1 = response.getEntity();
}
if (entity1 != null) {
result = EntityUtils.toString(entity1);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
public static String postMap(String url, Map<String, String> headerMap) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
List<NameValuePair> content = new ArrayList<NameValuePair>();
CloseableHttpResponse response = null;
try {
Iterator headerIterator = headerMap.entrySet().iterator(); //循环增加header
while (headerIterator.hasNext()) {
Map.Entry<String, String> elem = (Map.Entry<String, String>) headerIterator.next();
post.addHeader(elem.getKey(), elem.getValue());
}
if (content.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(content, "UTF-8");
post.setEntity(entity);
}
response = httpClient.execute(post); //发送请求并接收返回数据
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity(); //获取response的body部分
result = EntityUtils.toString(entity); //读取reponse的body部分并转化成字符串
}
return result;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 发送不带参数的HttpPost请求
* @param url
* @return
*/
public static String sendPost(String url) {
HttpPost httppost = new HttpPost(url);
CloseableHttpResponse response = null;
String result = null;
try {
CloseableHttpClient httpclient = getHttpClientInstance();
response = httpclient.execute(httppost);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* <p>此方法用于招行接口的请求,为适用执行请求编码格式为自定义
* @param url 请求URL
* @param body 请求传送的内容
* @param encoding 请求编码
* @return 请求返回的内容
* @author mengchen2
* @created 2017年10月14日 上午10:03:53
* @lasstModified mengchen2
*/
public static String sendPost(String url,String body,String encoding) {
HttpPost httppost = new HttpPost(url);
CloseableHttpResponse response = null;
String result = null;
try {
httppost.addHeader("Content-Type", "application/xml");
CloseableHttpClient httpclient = getHttpClientInstance();
StringEntity entity = new StringEntity(body, encoding);
entity.setContentType("text/xml");
entity.setContentEncoding(encoding);
httppost.setEntity(entity);
response = httpclient.execute(httppost);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity,encoding);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* <p>此方法用于招行接口的请求,为适用执行请求编码格式为自定义
* @param url 请求URL
* @param body 请求传送的内容
* @param encoding 请求编码
* @return 请求返回的内容
* @author mengchen2
* @created 2017年10月14日 上午10:03:53
* @lasstModified mengchen2
*/
public static String sendPost(String url,Map<String, String> header, String body,String encoding) {
HttpPost httppost = new HttpPost(url);
CloseableHttpResponse response = null;
String result = null;
try {
httppost.addHeader("Content-type","application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json");
if (MapUtils.isNotEmpty(header)){
Iterator headerIterator = header.entrySet().iterator(); //循环增加header
while (headerIterator.hasNext()) {
Map.Entry<String, String> elem = (Map.Entry<String, String>) headerIterator.next();
httppost.addHeader(elem.getKey(), elem.getValue());
}
}
CloseableHttpClient httpclient = getHttpClientInstance();
StringEntity entity = new StringEntity(body, encoding);
entity.setContentType("text/xml");
entity.setContentEncoding(encoding);
httppost.setEntity(entity);
response = httpclient.execute(httppost);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity,encoding);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 发送HttpPut请求
* @param url
* @return
*/
public static String sendPut(String url, Map<String, String> map) {
HttpPut httpPut = new HttpPut(url);
CloseableHttpResponse response = null;
String result = null;
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
httpPut.setEntity(entity);
try {
CloseableHttpClient httpclient = getHttpClientInstance();
response = httpclient.execute(httpPut);
} catch (IOException e1) {
log.error(e1.getMessage(), e1);
}
try {
HttpEntity entity1 = null;
if (response != null) {
entity1 = response.getEntity();
}
if (entity1 != null) {
result = EntityUtils.toString(entity1);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 发送HttpDelete请求
* @param url
* @return
*/
public static String sendDelete(String url) {
String result = null;
HttpDelete httpdelete = new HttpDelete(url);
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = getHttpClientInstance();
response = httpclient.execute(httpdelete);
} catch (IOException e1) {
log.error(e1.getMessage(), e1);
}
try {
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 发送post请求
*
* @param url
* @param header
* @param body
* @return
*/
public static String postWithHeader(String url, Map<String, String> header, String body) {
String result = "";
BufferedReader in = null;
PrintWriter out = null;
try {
// 设置 url
URL realUrl = new URL(url);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
// 设置 header
for (String key : header.keySet()) {
connection.setRequestProperty(key, header.get(key));
}
// 设置请求 body
connection.setDoOutput(true);
connection.setDoInput(true);
out = new PrintWriter(connection.getOutputStream());
// 保存body
out.print(body);
// 发送body
out.flush();
// 获取响应body
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
return result;
}
/**
* 发送get请求
*
* @param url
* @param header
* @return
*/
public static String getWithHeader(String url, Map<String, String> header) {
String result = "";
BufferedReader in = null;
try {
// 设置 url
URL realUrl = new URL(url);
URLConnection connection = realUrl.openConnection();
// 设置 header
for (String key : header.keySet()) {
connection.setRequestProperty(key, header.get(key));
}
// 设置请求 body
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
return result;
}
}
二、使用HttpsURLConnection发送https请求
1、发送https请求方式
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements 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;
}
}
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import com.alibaba.fastjson.JSONObject;
import com.demo.config.MyX509TrustManager;
public class HttpsUtil {
/**
* 发起https请求并获取结果 增加3秒超时时间
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setConnectTimeout(3000);
httpUrlConn.setReadTimeout(3000);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
System.out.println("Weixin server connection timed out.");
} catch (Exception e) {
System.out.println("https request error:{}"+e);
}
return jsonObject;
}
}
如现在需要在公众号中获取微信的昵称和头像,根据微信公众号官方文档 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839 调用的接口为:
返回的参数:
String accessToken = "******";
String openId = "******";
String wechatUrl = "https://api.weixin.qq.com/cgi-bin/user/info?
access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
String url = wechatUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID",
openId);
JSONObject result = HttpsUtil.httpRequest(url, "GET", null);
// 微信昵称
String nickname = result.getString("nickname");
//微信头像
String headimgurl = result.getString("headimgurl");
3、兼容https和http请求的util:
3.1、普通写法
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpsUtil {
/**
* 日志
*/
private static Logger log = LoggerFactory.getLogger(HttpsUtil.class);
/**
* 发送post请求,参数用map接收
* @param url 地址
* @param map 参数
* @return 返回值
*/
public static String postMap(String url, Map<String,String> map) {
String result = null;
CloseableHttpClient httpClient = wrapClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for(Map.Entry<String,String> entry : map.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
CloseableHttpResponse response = null;
try {
post.setEntity(new UrlEncodedFormEntity(pairs,"UTF-8"));
response = httpClient.execute(post);
if(response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (UnsupportedEncodingException e) {
log.error("UnsupportedEncodingException:" + e.getMessage(), e);
} catch (ClientProtocolException e) {
log.error("ClientProtocolException:" + e.getMessage(), e);
} catch (IOException e) {
log.error("IOException:" + e.getMessage(), e);
} finally {
try {
httpClient.close();
if(response != null) {
response.close();
}
} catch (IOException e) {
log.error("IOException2:" + e.getMessage(), e);
}
}
return null;
}
private static String entityToString(HttpEntity entity) throws IOException {
String result = null;
if(entity != null) {
long lenth = entity.getContentLength();
if(lenth != -1 && lenth < 2048) {
result = EntityUtils.toString(entity,"UTF-8");
} else {
InputStreamReader reader1 = null;
try {
reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
CharArrayBuffer buffer = new CharArrayBuffer(2048);
char[] tmp = new char[1024];
int l;
while ((l = reader1.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
result = buffer.toString();
} finally {
if (reader1 != null) {
reader1.close();
}
}
}
}
return result;
}
public static String doGet(String httpUrl) {
CloseableHttpClient httpClient = wrapClient();
CloseableHttpResponse response = null;
HttpGet get = new HttpGet(httpUrl);
String result = null;
try {
response = httpClient.execute(get);
if(response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
private static CloseableHttpClient wrapClient() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] {tm}, null);
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
return HttpClients.custom().setSSLSocketFactory(ssf).build();
} catch (Exception e) {
return HttpClients.createDefault();
}
}
}
3.2、使用连接池优化:
修改成连接池形式,避免每次调用开启新的连接:
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.cookie.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.*;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@SuppressWarnings("deprecation")
public class HttpsUtil {
private static volatile CloseableHttpClient httpclient = null;
private static Logger log = LoggerFactory.getLogger(HttpsUtil.class);
private HttpsUtil() {}
private static CloseableHttpClient getHttpClientInstance() {
if (httpclient == null) {
synchronized (HttpsUtil.class) {
if (httpclient == null) {
CookieSpecProvider csf = new CookieSpecProvider() {
@Override
public CookieSpec create(HttpContext context) {
return new BrowserCompatSpec() {
@Override
public void validate(Cookie cookie, CookieOrigin origin)
throws MalformedCookieException {
// Allow all cookies
}
};
}
};
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).setCookieSpec("easy").build();
httpclient = HttpClients.custom()
.setDefaultCookieSpecRegistry(RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.BEST_MATCH, csf)
.register(CookieSpecs.BROWSER_COMPATIBILITY, csf)
.register("easy", csf).build())
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(new DefaultHttpRequestRetryHandler())
.build();
}
}
}
return httpclient;
}
private static CloseableHttpClient wrapClient() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] {tm}, null);
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
return HttpClients.custom().setSSLSocketFactory(ssf).build();
} catch (Exception e) {
return HttpClients.createDefault();
}
}
public static String doGet(String httpUrl) {
CloseableHttpClient httpClient = wrapClient();
CloseableHttpResponse response = null;
HttpGet get = new HttpGet(httpUrl);
String result = null;
try {
response = httpClient.execute(get);
if(response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
private static String entityToString(HttpEntity entity) throws IOException {
String result = null;
if(entity != null) {
long lenth = entity.getContentLength();
if(lenth != -1 && lenth < 2048) {
result = EntityUtils.toString(entity,"UTF-8");
} else {
InputStreamReader reader1 = null;
try {
reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
CharArrayBuffer buffer = new CharArrayBuffer(2048);
char[] tmp = new char[1024];
int l;
while ((l = reader1.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
result = buffer.toString();
} finally {
if (reader1 != null) {
reader1.close();
}
}
}
}
return result;
}
/**
* 发送post请求,参数用map接收
* @param url 地址
* @param map 参数
* @return 返回值
*/
public static String postMap(String url, Map<String,String> map) {
String result = null;
CloseableHttpClient httpClient = wrapClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for(Map.Entry<String,String> entry : map.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
CloseableHttpResponse response = null;
try {
post.setEntity(new UrlEncodedFormEntity(pairs,"UTF-8"));
response = httpClient.execute(post);
if(response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (UnsupportedEncodingException e) {
log.error("UnsupportedEncodingException:" + e.getMessage(), e);
} catch (ClientProtocolException e) {
log.error("ClientProtocolException:" + e.getMessage(), e);
} catch (IOException e) {
log.error("IOException:" + e.getMessage(), e);
} finally {
try {
httpClient.close();
if(response != null) {
response.close();
}
} catch (IOException e) {
log.error("IOException2:" + e.getMessage(), e);
}
}
return null;
}
/**
* 发送HttpGet请求
* @param url
* @return
*/
public static String sendGet(String url) {
String result = null;
HttpGet httpget = new HttpGet(url);
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = getHttpClientInstance();
response = httpclient.execute(httpget);
} catch (IOException e1) {
log.error(e1.getMessage(), e1);
}
try {
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
public static String sendGet(String url, String userName, String password) {
String result = null;
CloseableHttpResponse response = null;
HttpHost target = new HttpHost("xxx.com", 443, "https");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(target.getHostName(), target.getPort()),
new UsernamePasswordCredentials(userName, password));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local
// auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(target, basicAuth);
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
HttpGet httpget = new HttpGet(url);
try {
response = httpclient.execute(target, httpget, localContext);
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 针对jira创建issue的方法
* @param url
* @param basicAuth
* @param postBody
* @return
*/
public static String executePostRequest(String url,String basicAuth ,String postBody) {
httpclient = HttpClients.createDefault();
ResponseHandler<String> handler = new BasicResponseHandler();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Authorization", basicAuth);
httpPost.setHeader("Content-type", "application/json");
StringEntity entity = new StringEntity(postBody, "UTF-8");
entity.setContentType("application/json;charset=UTF-8");
httpPost.setEntity(entity);
String responseBody = null;
HttpResponse response = null;
try {
response = httpclient.execute(httpPost);
responseBody = handler.handleResponse(response);
} catch (IOException e) {
System.out.println(e.getMessage() + " status code: " + response.getStatusLine().getStatusCode());
}
// String ticketNum = null;
// try {
// if (responseBody != null) {
// JSONObject result = JSONObject.parseObject(responseBody);
// ticketNum = result.getString("key");
// }
// } catch (JSONException e) {
// e.printStackTrace();
// }
// System.out.println("Ticket Number: " + ticketNum);
return responseBody;
}
public static String sendPost(String url, String userName, String password,String param) {
String result = null;
CloseableHttpResponse response = null;
HttpHost target = new HttpHost("xxx.com", 443, "https");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(target.getHostName(), target.getPort()),
new UsernamePasswordCredentials(userName, password));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local
// auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(target, basicAuth);
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
StringEntity entityParam = null;
try {
entityParam = new StringEntity(param);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
entityParam.setContentType("application/json");
// entityParam.setContentEncoding("utf-8");
httpPost.setEntity(entityParam);
try {
response = httpclient.execute(target, httpPost, localContext);
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 发送HttpPost请求,参数为map
* @param url
* @param map
* @return
*/
public static String sendPost(String url, Map<String, String> map) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
HttpPost httppost = new HttpPost(url);
httppost.setEntity(entity);
CloseableHttpResponse response = null;
String result = null;
try {
CloseableHttpClient httpclient = getHttpClientInstance();
response = httpclient.execute(httppost);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
HttpEntity entity1 = null;
if (response != null) {
entity1 = response.getEntity();
}
if (entity1 != null) {
result = EntityUtils.toString(entity1);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 发送不带参数的HttpPost请求
* @param url
* @return
*/
public static String sendPost(String url) {
HttpPost httppost = new HttpPost(url);
CloseableHttpResponse response = null;
String result = null;
try {
CloseableHttpClient httpclient = getHttpClientInstance();
response = httpclient.execute(httppost);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* <p>此方法用于招行接口的请求,为适用执行请求编码格式为自定义
* @param url 请求URL
* @param body 请求传送的内容
* @param encoding 请求编码
* @return 请求返回的内容
* @author mengchen2
* @created 2017年10月14日 上午10:03:53
* @lasstModified mengchen2
*/
public static String sendPost(String url,String body,String encoding) {
HttpPost httppost = new HttpPost(url);
CloseableHttpResponse response = null;
String result = null;
try {
httppost.addHeader("Content-Type", "application/xml");
CloseableHttpClient httpclient = getHttpClientInstance();
StringEntity entity = new StringEntity(body, encoding);
entity.setContentType("text/xml");
entity.setContentEncoding(encoding);
httppost.setEntity(entity);
response = httpclient.execute(httppost);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity,encoding);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 发送HttpPut请求
* @param url
* @return
*/
public static String sendPut(String url, Map<String, String> map) {
HttpPut httpPut = new HttpPut(url);
CloseableHttpResponse response = null;
String result = null;
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
httpPut.setEntity(entity);
try {
CloseableHttpClient httpclient = getHttpClientInstance();
response = httpclient.execute(httpPut);
} catch (IOException e1) {
log.error(e1.getMessage(), e1);
}
try {
HttpEntity entity1 = null;
if (response != null) {
entity1 = response.getEntity();
}
if (entity1 != null) {
result = EntityUtils.toString(entity1);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 发送HttpDelete请求
* @param url
* @return
*/
public static String sendDelete(String url) {
String result = null;
HttpDelete httpdelete = new HttpDelete(url);
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = getHttpClientInstance();
response = httpclient.execute(httpdelete);
} catch (IOException e1) {
log.error(e1.getMessage(), e1);
}
try {
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return result;
}
/**
* 发送post请求
*
* @param url
* @param header
* @param body
* @return
*/
public static String postWithHeader(String url, Map<String, String> header, String body) {
String result = "";
BufferedReader in = null;
PrintWriter out = null;
try {
// 设置 url
URL realUrl = new URL(url);
URLConnection connection = realUrl.openConnection();
// 设置 header
for (String key : header.keySet()) {
connection.setRequestProperty(key, header.get(key));
}
// 设置请求 body
connection.setDoOutput(true);
connection.setDoInput(true);
out = new PrintWriter(connection.getOutputStream());
// 保存body
out.print(body);
// 发送body
out.flush();
// 获取响应body
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
return result;
}
/**
* 发送get请求
*
* @param url
* @param header
* @return
*/
public static String getWithHeader(String url, Map<String, String> header) {
String result = "";
BufferedReader in = null;
try {
// 设置 url
URL realUrl = new URL(url);
URLConnection connection = realUrl.openConnection();
// 设置 header
for (String key : header.keySet()) {
connection.setRequestProperty(key, header.get(key));
}
// 设置请求 body
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
return result;
}
}
三、使用java自带的RestTemplate发送http、https请求
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}