码迷,mamicode.com
首页 > Web开发 > 详细

httpclient 发送一个请求

时间:2014-10-20 17:04:41      阅读:153      评论:0      收藏:0      [点我收藏+]

标签: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 发送一个请求

标签:style   blog   http   color   io   os   ar   for   strong   

原文地址:http://www.cnblogs.com/killbug/p/4037488.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!