package com.ecosm.itsm.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
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.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
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.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
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.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
@SuppressWarnings("deprecation")
public class HttpRequest {
/**
* 向指定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;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
* HttpClient POST方式发起http请求
*/
@SuppressWarnings("unused")
public static String SendClientPost(String url ,String paramflg,String param){
String result ="";
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse httpResponse = null;
try {
HttpPost post = new HttpPost(url);
//创建参数列表
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair(paramflg,param));
//url格式编码
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list,"UTF-8");
post.setEntity(uefEntity);
//执行请求
httpResponse = httpClient.execute(post);
HttpEntity entity = httpResponse.getEntity();
if (null != entity){
return EntityUtils.toString(entity, "utf-8");
}
} catch(Exception e){
e.printStackTrace();
}finally{
try{
httpResponse.close();
closeHttpClient(httpClient);
} catch(Exception e){
e.printStackTrace();
}
}
return null;
}
/**
* HttpClient GET方式发起http请求
*/
public static String SendClinetGet(String url){
String result = "";
//创建默认的httpClient实例
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse httpResponse = null;
try {
//用get方法发送http请求
HttpGet get = new HttpGet(url);
//发送get请求
httpResponse = httpClient.execute(get);
//response实体
HttpEntity entity = httpResponse.getEntity();
if(entity !=null){
//System.out.println("响应状态码:"+ httpResponse.getStatusLine());
result = EntityUtils.toString(entity);
}
}catch (Exception e) {
e.printStackTrace();
}finally{
try{
httpResponse.close();
closeHttpClient(httpClient);
} catch (IOException e){
e.printStackTrace();
}
}
return result;
}
private static CloseableHttpClient getHttpClient(){
return HttpClients.createDefault();
}
private static void closeHttpClient(CloseableHttpClient client) throws IOException{
if (client != null){
client.close();
}
}
/**
* get跨域操作
* @param pd
* @return
*/
@SuppressWarnings({ "resource", "unused" })
public static String HttpGet(String url){
HttpGet method = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
String body = "";
if (null != method){
try {
//建立一个NameValuePair数组,用于存储欲传送的参数
//method.addHeader("Content-type","application/x-www-form-urlencoded; charset=utf-8");
method.addHeader("Content-type","application/json; charset=utf-8");
method.setHeader("Accept", "application/json");
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
// pairList.add(new BasicNameValuePair("app_id",String.valueOf( new Date() ) ));
// method.setEntity((new UrlEncodedFormEntity(pairList,HTTP.UTF_8)));
HttpResponse response = httpClient.execute(method);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
//body = EntityUtils.toString(response.getEntity());
}
body = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
body = "500";
}
}
return body;
}
private static Logger logger = Logger.getLogger(HttpRequest.class);
/**
* 跨域Post
* @param url 地址
* @param param 参数
* @return
*/
//public static String SendClientPost(String url ,String paramflg,String param){
@SuppressWarnings({ "unused", "unchecked" })
public static String HttpPost(String url ,PageData param){
String result ="";
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse httpResponse = null;
try {
logger.info("---进入try---");
HttpPost post = new HttpPost(url);
//创建参数列表
List<NameValuePair> list = new ArrayList<NameValuePair>();
logger.info("---开始设置POST参数---");
Set<Object> s = param.keySet();
for(Object key:s){
list.add(new BasicNameValuePair(key.toString(),param.getString(key)));
}
//url格式编码
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list,"UTF-8");
post.setEntity(uefEntity);
logger.info("---设置参数结束---");
//执行请求
httpResponse = httpClient.execute(post);
HttpEntity entity = httpResponse.getEntity();
if (null != entity){
return EntityUtils.toString(entity, "utf-8");
}
} catch(Exception e){
logger.info("---报错1!"+e.getMessage()+"---");
e.printStackTrace();
}finally{
try{
httpResponse.close();
closeHttpClient(httpClient);
} catch(Exception e){
logger.info("---报错2!"+e.getMessage()+"---");
e.printStackTrace();
}
}
return null;
}
public static String HttpPostWithJson(String url, String json) {
String returnValue = "这是默认返回值,接口调用失败";
CloseableHttpClient httpClient = HttpClients.createDefault();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try{
//第一步:创建HttpClient对象
httpClient = HttpClients.createDefault();
//第二步:创建httpPost对象
HttpPost httpPost = new HttpPost(url);
//第三步:给httpPost设置JSON格式的参数
StringEntity requestEntity = new StringEntity(json,"utf-8");
requestEntity.setContentEncoding("UTF-8");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(requestEntity);
//第四步:发送HttpPost请求,获取返回值
returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时,必须用此方法
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//第五步:处理返回值
return returnValue;
}
public static String httpPostRequest1(String url) throws Exception {
HttpPost post = new HttpPost(url);
CloseableHttpClient httpClient = getHttpClient();
try {
CloseableHttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
response.close();
return result;
}
} catch (ClientProtocolException var5) {
var5.printStackTrace();
} catch (IOException var6) {
var6.printStackTrace();
}
return "httpUrlError";
}
/**
* 1.发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
@SuppressWarnings("restriction")
public static JSONObject httpRequests(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);
URL url= new URL(null, requestUrl, new sun.net.www.protocol.https.Handler());
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(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();
try {
jsonObject =JSONObject.parseObject(buffer.toString());
} catch (Exception e) {
String reString = buffer.toString();
String rs = new String(Base64.getDecoder().decode(reString));
jsonObject =JSONObject.parseObject(rs);
}
} catch (ConnectException ce) {
logger.error("Weixin server connection timed out.",ce);
} catch (Exception e) {
logger.error("https request error:{}",e);
}
return jsonObject;
}
}
HTTP请求工具类,包含各种发送方式
最新推荐文章于 2024-02-22 20:02:20 发布