httpclient 發送一個請求

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   ar   for   strong   

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:

    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請求

    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都不相同。

還有需要注意的是3中逾時:

1,連線逾時:connectionTimeout 指的是串連一個url的串連等待時間。

2,讀取資料逾時:soTimeout  指的是串連上一個url,擷取response的返回等待時間

3,SocketTimeout :定義了Socket讀資料的逾時時間,即從伺服器擷取響應資料需要等待的時間

    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;    }

 

 

 

httpclient 發送一個請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.