Http工具类,Lz提供

Posted lifan12589

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Http工具类,Lz提供相关的知识,希望对你有一定的参考价值。

package com.wondersgroup.TransportCommission;

import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

/**
* Http工具类,发送Http请求 交通委提供
*
* @author 10036
*/

@SuppressWarnings("deprecation")
public class HttpClientConnectionManager {

private static Logger logger = LoggerFactory.getLogger(HttpClientConnectionManager.class); // 日志记录
private static final CloseableHttpClient httpclient = HttpClients.createDefault();
private static final String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/54.0.2840.87 Safari/537.36";
private static org.apache.log4j.Logger logger1 = org.apache.log4j.Logger.getLogger("wpLog");



public static void main(String[] args) {
String url = "https://wsbs.jt.sh.cn/common-interface/getRoadInfoServlet?type=1&serviceid=fcedf9a2116549c395f44b1ba70529bd";
String responsedata2 = HttpClientConnectionManager.sendPostRequest(url, "", "POST", "");
System.out.println(responsedata2);

}


/**
* 向server端发送请求,并获取返回参数
*
* @param actionUrl
* @param method
* @param param
* @return
*/
public static String sendPostRequest(String serverUrl, String actionUrl, String method, String param) {
logger.debug("+++++++++++++++sendPostRequest方法开始!+++++++++++++++++++");
logger.debug("serverUrl:" + serverUrl);
logger.debug("actionUrl:" + actionUrl);
logger.debug("param:" + param);

StringBuffer sb = new StringBuffer();
String output = "";
try {
// System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
URL url = new URL(serverUrl + actionUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Charset", "utf-8");
conn.setRequestProperty("Content-Type", "application/json");

//解决乱码代码
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");

if (param != null) {
OutputStream os = conn.getOutputStream();
os.write(param.getBytes("utf-8"));
os.flush();
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
} catch (Exception e) {
logger.error("+++++++++++++++send post exception!+++++++++++++++++++");
logger.error("Request: url=" + serverUrl + actionUrl + "; param=" + param);
logger.error("Error message:" + e.getMessage());
logger.error("output:" + output);
e.printStackTrace();
}
return String.valueOf(sb);
}

/**
* 向server端发送请求,并获取返回参数
*
* @return
* @throws UnsupportedEncodingException
*/
public static String sendGetRequest(String targetURL) throws UnsupportedEncodingException {
logger.debug("+++++++++++++++sendGetRequest方法开始!+++++++++++++++++++");
logger.debug("targetURL:" + targetURL);
String output = "";
String outStr = "";
try {
URL restServiceURL = new URL(targetURL);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Charset", "utf-8");
httpConnection.setRequestProperty("Content-Type", "application/json");

//解决乱码代码
httpConnection.setRequestProperty("Accept-Charset", "utf-8");
httpConnection.setRequestProperty("Accept-Encoding", "utf-8");

if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), "utf-8"));
while ((output = responseBuffer.readLine()) != null) {
outStr = outStr + output;
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
logger.error("+++++++++++++++send get exception!+++++++++++++++++++");
logger.error("Request: url=" + targetURL);
logger.error("Error message:" + e.getMessage());
logger.error("output:" + output);
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return outStr;
}

public static JSONObject httpPost(String url, JSONObject jsonParam, boolean noNeedResponse){
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
JSONObject jsonResult = null;
HttpPost postMethod = null;
HttpPost method = new HttpPost(url);
logger1.debug("url:" + url);
try {
logger1.debug("json数据:"+jsonParam.toString() );
if (null != jsonParam) {
method.addHeader("Content-Type", "application/json");
method.addHeader("account", "admin");
//解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
logger1.debug("entity:" + entity.toString());
}
logger1.debug("发送请求:" );
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
logger1.debug("请求发送成功,并得到响应:" );
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
logger1.debug("请求发送成功,并得到响应:200" );
String str = "";
try {
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity());
logger1.debug("读取服务器返回过来的json字符串数据:" + str);
if (noNeedResponse) {
return null;
}
/**把json字符串转换成json对象**/
jsonResult = JSONObject.fromObject(str);
} catch (Exception e) {
logger1.debug("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
logger1.debug("post请求提交失败:" + url, e);
}
return jsonResult;
}
}

以上是关于Http工具类,Lz提供的主要内容,如果未能解决你的问题,请参考以下文章

Cookie工具类 - CookieUtil.java

Android中获取手机IMEI,IMSI, MAC(Android 6.0支持4G环境获取)工具类(标识用户唯一)

roidba的最爱,lz4压缩工具,备份恢复再也不用等几个小时了啦

Cygwin(类UNIX模拟环境)&CURL(强大的http命令行工具)

JavaWeb之抓包之旅 :HttpClient封装工具类

Collections工具类:操作集合的工具类