httpclient 發送一個請求

httpclient版本 4.1
發送一個post請求
    public static JSONObject post(String url,JSONObject json){  
            HttpClient client = new DefaultHttpClient();  
            HttpPost post = new HttpPost(url);  
            JSONObject response = null;  
            try {  
                StringEntity s = new StringEntity(json.toString());  
                s.setContentEncoding("UTF-8");  
                s.setContentType("application/json");  
                post.setEntity(s);  
                   
                 HttpResponse res = client.execute(post);  
                 if(res.getStatusLine().getStatusCode() == HttpStatus.OK.value()){  
                     HttpEntity entity = res.getEntity();  
                     String charset = EntityUtils.getContentCharSet(entity);  
                     response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(),charset)));  
                 }  
             } catch (Exception e) {  
                 throw new RuntimeException(e);  
             }  
             return response;  
         }  

模擬提交form:json

    private static HttpPost postForm(String url, Map<String, String> params){  
          
        HttpPost httpost = new HttpPost(url);  
        List<NameValuePair> nvps = new ArrayList <NameValuePair>();  
          
        Set<String> keySet = params.keySet();  
        for(String key : keySet) {  
            nvps.add(new BasicNameValuePair(key, params.get(key)));  
        }  
           
         try {  
             log.info("set utf-8 form entity to httppost");  
             httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));  
         } catch (UnsupportedEncodingException e) {  
             e.printStackTrace();  
         }  
           
         return httpost;  
     }  

get請求api

    public static String get(String url) {  
           DefaultHttpClient httpclient = new DefaultHttpClient();  
           String body = null;  
             
           log.info("create httppost:" + url);  
           HttpGet get = new HttpGet(url);  
           body = invoke(httpclient, get);  
             
           httpclient.getConnectionManager().shutdown();  
              
            return body;  
        }

發起一個post請求,設置超時:服務器

須要注意各個版本設置超時的api都不相同。app

還有須要注意的是3中超時:post

1,鏈接超時:connectionTimeout 指的是鏈接一個url的鏈接等待時間。ui

2,讀取數據超時:soTimeout  指的是鏈接上一個url,獲取response的返回等待時間

3,SocketTimeout :定義了Socket讀數據的超時時間,即從服務器獲取響應數據須要等待的時間url

    public static String sendPostRequest(String url, String str, String contentType, String charset){
//        HttpParams httpParams = new BasicHttpParams();//4.1版本
//        HttpConnectionParams.setConnectionTimeout(httpParams, 5000);//創建鏈接超時時間,防止調用url爲死鏈,消耗服務器io
//        HttpConnectionParams.setSoTimeout(httpParams, 3000);// 響應超時
//        CloseableHttpClient httpClient = new DefaultHttpClient(); 
        RequestConfig.Builder requestBuilder = RequestConfig.custom();//4.3.5版本
        requestBuilder = requestBuilder.setConnectTimeout(5000);
        //requestBuilder = requestBuilder.setConnectionRequestTimeout(100);

        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setDefaultRequestConfig(requestBuilder.build());
        CloseableHttpClient httpClient = builder.build();
        
        HttpPost post = new HttpPost(url); 
        //RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        //post.setConfig(requestConfig);
        post.setHeader("Content-Type", contentType); 
        ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
        String response = null;
        try {
            post.setEntity(new StringEntity(str, charset));
            long start = System.currentTimeMillis();
            try {
                response = httpClient.execute(post,responseHandler); 
            } catch (Exception ConnectionTimeoutException) {//創建鏈接超時異常
                long p = System.currentTimeMillis() - start;
                log.error("sendPostRequest has a ConnectionTimeoutException timeout=> "+ p +"  "+ url);
            }finally{
                //httpClient.getConnectionManager().shutdown();
                post.releaseConnection();
            }
        } catch (Exception e) {
            log.error("執行HTTP Post請求" + url + "時,發生異常!", e);
        }
        return response;
    }
相關文章
相關標籤/搜索