| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- package cn.com.goldenwater.dcproj.utils;
- import cn.com.goldenwater.dcproj.constValue.CommonLabel;
- 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.HttpClients;
- import org.apache.http.util.EntityUtils;
- import javax.servlet.http.HttpServletRequest;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.URI;
- import java.net.URL;
- import java.net.URLConnection;
- import java.nio.charset.Charset;
- public class HttpUtil {
- public String getHttpResponse(String allConfigUrl) {
- BufferedReader in = null;
- StringBuffer result = new StringBuffer();
- try {
- // url请求中如果有中文,要在接收方用相应字符转码
- URI uri = new URI(allConfigUrl);
- URL url = uri.toURL();
- URLConnection connection = url.openConnection();
- connection.setRequestProperty("Content-type", "text/html");
- connection.setRequestProperty("Accept-Charset", "utf-8");
- connection.setRequestProperty("contentType", "utf-8");
- connection.setConnectTimeout(300000);
- connection.connect();
- // 读取URL的响应
- in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
- String line;
- while ((line = in.readLine()) != null) {
- result.append(line);
- }
- return result.toString();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (in != null) {
- in.close();
- }
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return result.toString();
- }
- public static String resultBody(String url, Object params, HttpServletRequest request){
- String content = "";
- CloseableHttpClient httpCilent = HttpClients.createDefault();
- HttpPost httpPost = new HttpPost(url);
- JSONObject jsonObject = JSONObject.fromObject(params);
- try {
- httpPost.addHeader("Content-type", "application/json; charset=utf-8");
- httpPost.setHeader("Accept", "application/json");
- httpPost.setHeader(CommonLabel.ORGId,request.getHeader(CommonLabel.ORGId));
- httpPost.setHeader(CommonLabel.PERSID,request.getHeader(CommonLabel.PERSID));
- httpPost.setHeader(CommonLabel.ACCESS_TOKEN,request.getHeader(CommonLabel.ACCESS_TOKEN));
- httpPost.setEntity(new StringEntity(jsonObject.toString(), Charset.forName("UTF-8")));
- HttpResponse httpResponse = httpCilent.execute(httpPost);
- if (httpResponse.getStatusLine().getStatusCode() == 200) {
- content = EntityUtils.toString(httpResponse.getEntity());
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- httpCilent.close();//释放资源
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return content;
- }
- }
|