HttpClient请求URL

Posted 十一路客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();      
   	
   	

 

以上是关于HttpClient请求URL的主要内容,如果未能解决你的问题,请参考以下文章

HttpClient请求URL

为啥HttpClient请求返回400,URL请求返回302正常

通过 HttpClient 禁用单个 url 的请求日志记录

httpclient的几种请求URL的方式

为啥 System.Net.Http HttpClient 对我的请求 URL 进行编码?

C# HttpClient.SendAsync 在测试某些 URL 时抛出“发送请求时发生错误”异常