Http工具类,Lz提供

package com.util;

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请求 Lz提供
*
* @author 10036
*/

@SuppressWarnings("deprecation")
public class HttpClientConnectionManager {

private static Logger logger = LoggerFactory.getLogger(HttpClientConnectionManager.class); // 日志记录
private static org.apache.log4j.Logger logger1 = org.apache.log4j.Logger.getLogger("wpLog");



public static void main(String[] args) {
String url = "https:/?type=1&serviceid=4b1ba70529bd";
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;
}
}

posted @ 2019-10-21 10:47  Li&Fan  阅读(378)  评论(0编辑  收藏  举报