HttpUtil

package com.hlg.xboot.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

public class HttpUtil {
	private static Logger logger = Logger.getLogger(HttpUtil.class);
	
	public static String doPostJson(String url, String param) throws Exception {
		logger.warn("doPostJson   url="+url+" ; param="+param);
		String responseBody = "";
		HttpPost httppost = new HttpPost(url);
		StringEntity entities = new StringEntity(param, "UTF-8");
		entities.setContentEncoding("UTF-8");
		entities.setContentType("application/json");
		httppost.setEntity(entities);
		ResponseHandler responseHandler = new ResponseHandler() {

			public String handleResponse(final HttpResponse response)
					throws ClientProtocolException, IOException {
				int status = response.getStatusLine().getStatusCode();
				if (status >= 200 && status < 300) {
					HttpEntity entity = response.getEntity();
					return entity != null ? EntityUtils.toString(entity)
							: null;
				} else {
					throw new ClientProtocolException(
							"Unexpected response status: " + status);
				}
			}
		};
//		try {
			responseBody = HttpClientBuilder.create().build().execute(httppost, responseHandler);
//		} catch (SocketTimeoutException e) {
//			e.printStackTrace();
//			responseBody = "timeout";
//			return responseBody;
//		} catch (ClientProtocolException e) {
//			e.printStackTrace();
//			return responseBody;
//		} catch (IOException e) {
//			e.printStackTrace();
//			return responseBody;
//		}
		return responseBody;
	}
	
	public static String executeGet(String url) throws Exception {
        BufferedReader in = null;
  
        String content = null;
        try {  
            // 定义HttpClient  
            CloseableHttpClient client = HttpClientBuilder.create().build();
            // 实例化HTTP方法  
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
  
            in = new BufferedReader(new InputStreamReader(response.getEntity()
                    .getContent()));  
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {  
                sb.append(line + NL);  
            }  
            in.close();  
            content = sb.toString();  
        } finally {  
            if (in != null) {  
                try {  
                    in.close();// 最后要关闭BufferedReader  
                } catch (Exception e) {
                    e.printStackTrace();  
                }  
            }  
            return content;  
        }  
    }

	/**
	 *
	 * 发送HTTP_GET请求
	 * 该方法会自动关闭连接,释放资源
	 * @param reqURL    请求地址(含参数)
	 * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
	 * @return 远程主机响应正文
     */
	public static String sendGetRequest(String reqURL, String decodeCharset) throws IOException {
		long responseLength = 0;       //响应长度
		String responseContent = null; //响应内容
		CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //创建默认的httpClient实例
		HttpGet httpGet = new HttpGet(reqURL);           //创建org.apache.http.client.methods.HttpGet
		try{
			HttpResponse response = httpClient.execute(httpGet); //执行GET请求
			HttpEntity entity = response.getEntity();            //获取响应实体
			if(null != entity){
				responseLength = entity.getContentLength();
				responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
				EntityUtils.consume(entity); //Consume response content
			}
//			System.out.println("请求地址: " + httpGet.getURI());
//			System.out.println("响应状态: " + response.getStatusLine());
//			System.out.println("响应长度: " + responseLength);
//			System.out.println("响应内容: " + responseContent);
		}catch(ClientProtocolException e){
			logger.debug("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);
		}catch(ParseException e){
			logger.debug(e.getMessage(), e);
		}catch(IOException e){
			logger.debug("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
		}finally{
			httpClient.close(); //关闭连接,释放资源
		}
		return responseContent;
	}

	public static void main(String[] args) throws IOException {
        String url = "";
		String s = sendGetRequest(url, null);
		System.out.println(JSON.toJSON(s));
	}
}


使用
private Gson gson = new Gson();

Map remoteParamsMap = new HashMap<>();
        map.put("project_id", params.get("projectId"));
        //map.put("task_date_start", starDate);
        map.put("date_start", starDate);
        //map.put("task_date_end", endDate);
        map.put("date_end", endDate);
        remoteParamsMap.put("param", map);

try {
            //月度单品数据 SKU商品效果 OK
            String monthJson = HttpUtil.doPostJson("http://127.0.0.1:8024/oralb/select_product_sku/", gson.toJson(remoteParamsMap));
            JSONObject json = JSONObject.fromObject(monthJson);
            JSONArray jsonArray = JSONArray.fromObject(json.getString("data"));
            resultMap.put("月度单品数据", jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }

 

你可能感兴趣的:(Http)