HttpClient请求URL

1. 编写HttpClientUtil做POST和GET请求

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by alibaba on 2017/11/8.
 */
public class HttpClientUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     * @param url 请求地址
     * @param param 请求参数
     *
     * @return map - status 返回状态 1-失败 0-成功 Integer
     * @return map - result 失败原因 or 请求成功后api的返回信息 String
     * */
    public static HashMap<String, Object> doPost(String url, Map<String,Object> param){
        logger.info("url: " + url);
        String result = "";
        Integer status = 0;
        HashMap<String,Object> returnMap = new HashMap<String,Object>();
        try {
                HttpClient client = HttpClients.createDefault();
                HttpPost request = new HttpPost(url);

                String jsonStr = "";
                if(param != null) {
                    jsonStr = JSON.toJSONString(param);
                }
                logger.info("jsonStr: " + jsonStr);
                StringEntity requestEntity = new StringEntity(jsonStr, "UTF-8");
                requestEntity.setContentType("application/json;charset=UTF-8");
                request.setEntity(requestEntity);
                HttpResponse response = client.execute(request);
                if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
                    HttpEntity responseEntity = response.getEntity();
                    if(responseEntity != null){
                        status = 0;
                        result = EntityUtils.toString(responseEntity,"UTF-8");
                    }else{
                        status = 1;
                        result = "POST接口响应实体为空!";
                    }
                }else{
                    status = 1;
                    result = "POST接口请求出错!";
                }


        } catch (Exception e) {
               e.printStackTrace();
               status = 1;
               result = "POST接口调用出现异常,exception: " + e.toString();
        }

        if(status == 1){
            logger.error("POST接口【" + url +"】请求出错! 出错信息为: " + result);
        }

        returnMap.put("status", status);
        returnMap.put("result", result);

        return returnMap;
    }

    /**
     * @param url 请求地址
     * @param param 请求参数
     *
     * @return map - status 返回状态 1-失败 0-成功 Integer
     * @return map - result 失败原因 or 请求成功后api的返回信息 String
     * */
    public static HashMap<String, Object> doGet(String url, Map<String,Object> param){
        logger.info("Get url: " + url);
        String result = "";
        Integer status = 0;
        HashMap<String,Object> returnMap = new HashMap<String,Object>();
        try {
            HttpClient client = HttpClients.createDefault();

            String paramStr = "";
            if (param != null) {
                StringBuilder myStringBuilder = new StringBuilder("?");
                Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
                while (it.hasNext())
                {
                    Map.Entry<String, Object> entry = it.next();
                    Object key = entry.getKey();
                    myStringBuilder.append(key);
                    myStringBuilder.append('=');
                    String value = entry.getValue().toString();
                    myStringBuilder.append(URLEncoder.encode(value, "UTF-8"));
                    if (it.hasNext())
                    {
                        myStringBuilder.append("&");
                    }
                }

                paramStr = myStringBuilder.toString();
            }

            String newUrl = url + paramStr;
            logger.info("GET url : " + newUrl);
            HttpGet request = new HttpGet(newUrl);


            HttpResponse response = client.execute(request);
            if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
                HttpEntity responseEntity = response.getEntity();
                if(responseEntity != null){
                    status = 0;
                    result = EntityUtils.toString(responseEntity,"UTF-8");
                }else{
                    status = 1;
                    result = "GET接口响应实体为空!";
                }

            }else{
                status = 1;
                result = "GET接口请求出错!";
            }


        } catch (Exception e) {
            e.printStackTrace();
            status = 1;
            result = "GET接口调用出现异常,exception: " + e.toString();
        }

        if(status == 1){
            logger.error( "GET接口【" + url +"】请求出错! 出错信息为: " + result);
        }

        returnMap.put("status", status);
        returnMap.put("result", result);

        return returnMap;
    }

  /*  public static void main(String[] args) {
        //测试doget
        String url = "http://XX.XX.XX.XX";
        HashMap<String, Object> param = new HashMap<String, Object>();
        param.put("from", 1510120000);
        param.put("to", 1510128912);

        HashMap<String, Object> returnMap = HttpClientUtil.doGet(url, param);

        Integer status = (Integer)returnMap.get("status");
        String result = (String)returnMap.get("result");

        logger.info("doGet status: " + status);
        logger.info("doGet result: " + result);

        //测试dopost
//        String url = "http://XXX.XX.XX.XX/api";
//        HashMap<String, Object> param = new HashMap<String, Object>();
//        param.put("key", "XXXX-XXXX-XXX-XXXX-XXXX");
//        param.put("user","test");
//        param.put("method", "testMethod");
//
//        HashMap<String, Object> returnMap = HttpClientUtil.doPost(url, param);
//
//        Integer status = (Integer)returnMap.get("status");
//        String result = (String)returnMap.get("result");
//
//        logger.info("doPost status: " + status);
//        logger.info("doPost result: " + result);
    }*/
}

2. 调用doPost或doGet方法请求URL

  /**
     * 请求url
     * @param param 对接字段封装对象
     * @return map - status 返回状态 1-失败 0-成功 Integer
     * @return map - result 失败原因 
     * */
	public static HashMap<String, Object> dispatchUrl(Object param) {
		// TODO Auto-generated method stub
		String url = Constants.API_URL;	
		 //请求参数
	    Map<String,Object> param = new HashMap<String,Object>();  
	    param.put("key", "XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX");
	    param.put("user","test");
	    param.put("method", "testMethod");
	    param.put("data", param);
	    
	    logger.info("JSON.toJSONString(param): " + JSON.toJSONString(param));	  
	    HashMap<String,Object> returnMap = new HashMap<String, Object>();
	 	   
	    //处理返回结果
	    returnMap = HttpClientUtil.doPost(url, param, "UTF-8");
	    String responseResult = (String)returnMap.get("result");
	    Integer status = (Integer)returnMap.get("status");
	    logger.info("status: " + status + "; responseResult: " + responseResult);
	   
	    if(status.equals(1)){//后台出错 请求出错
	    	return returnMap;
	    }	    
	    Integer statusCode = 0;
	    JSONObject obj = JSONObject.parseObject(responseResult);
		statusCode = (Integer)obj.get("statusCode");
		
		//状态码为失败
		if(statusCode == null || statusCode.equals(1)){
			returnMap.put("status", 1);
			returnMap.put("result", (String)obj.get("errorMessage"));
			return returnMap;
		}		
		//无responseData
		//String dataStr = obj.get("responseData").toString();		
	    return returnMap;	
	} 
    
      
     public static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {

   		StringBuilder sb1 = new StringBuilder();      
           byte[] bytes = new byte[4096];    
           int size = 0;                 
           try {      
               while ((size = is.read(bytes)) > 0) {    
                   String str = new String(bytes, 0, size, "UTF-8");    
                   sb1.append(str);    
               }    
           } catch (IOException e) {      
               e.printStackTrace();      
           } finally {      
               try {      
                   is.close();      
               } catch (IOException e) {      
                  e.printStackTrace();      
               }      
           }      
           return sb1.toString();      
   	}
   	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值