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

httpcomponents-client-4.3.6 HttpPost的简单使用

时间:2014-12-16 13:13:21      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   io   color   os   使用   sp   

/**
 *  httpcomponents-client-4.3.6
 * @author y
 */
public class HttpUtil {
    
    public static String httpPost( List<NameValuePair> formparams,final String url){
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        
        //设置网络超时
        RequestConfig config = RequestConfig.custom()
                .setConnectionRequestTimeout(3*1000)
                .setConnectTimeout(3*1000)
                .setSocketTimeout(3*1000)
                .build();
        
        HttpPost httppost = new HttpPost(url);
        httppost.setConfig(config);
        httppost.setEntity(entity);
        
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        
        String reuslt = "";
        
        try {
            response = httpclient.execute(httppost);
            
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entityContent = response.getEntity();
                if (entityContent != null) {
                    reuslt = EntityUtils.toString(entityContent, Consts.UTF_8); //指定编码格式防止中文乱码
                }
            }else{
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, "网络链接超时");
            }
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }finally {
            try{
                if(response!=null){
                    response.close();
                }
            }catch (IOException ex) {
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        return reuslt;
    }
    
}

 

httpcomponents-client-4.3.6 HttpPost的简单使用

标签:style   blog   http   ar   io   color   os   使用   sp   

原文地址:http://www.cnblogs.com/yshyee/p/4166828.html

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