国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

httpclient 發送一個請求

2019-11-14 21:23:24
字體:
來源:轉載
供稿:網友
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:

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 马关县| 雅安市| 平泉县| 绍兴市| 广南县| 清涧县| 康平县| 高陵县| 新密市| 赤城县| 锦州市| 建瓯市| 阜新市| 麦盖提县| 永年县| 靖江市| 房产| 石林| 山丹县| 蒙自县| 察哈| 永泰县| 靖西县| 阿鲁科尔沁旗| 武汉市| 广平县| 呼伦贝尔市| 乐至县| 温泉县| 汶川县| 苏州市| 东阿县| 万年县| 惠水县| 阳江市| 政和县| 德江县| 巴楚县| 穆棱市| 张家口市| 乌海市|