HttpClient 的GET(带参数)、POST请求方式,工具类方法

/**
 * 连接/断开操作 post方式
 * @param url
 * @param json
 */
private boolean connOrDisconnOperator(String url,String json){
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    boolean flag = false;
    try{
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000)
                .setSocketTimeout(50000)
                .setConnectionRequestTimeout(120000).build();
        httpPost.setConfig(requestConfig);
        List<BasicNameValuePair> list = Lists.newArrayListWithExpectedSize(1);
        list.add(new BasicNameValuePair("json",json));
        httpPost.setEntity(new UrlEncodedFormEntity(list));
        client = HttpClients.createDefault();
        response = client.execute(httpPost);
        if(response.getStatusLine().getStatusCode() == 200){
            InputStream is = response.getEntity().getContent();
            Map<String,Object> m = new ObjectMapper().readValue(StringUtil.getString(is),Map.class);
            String strState = m.get("state").toString();
            if("SUCCESS".equals(strState)){
                flag = true;
            }
        }else{
            log.error(this.getClass(), "connOrDisconnOperator method fail:" + response.getStatusLine().getStatusCode());
        }
    }catch (Exception ex){
        log.error(this.getClass(), "connOrDisconnOperator method error",ex);
    }finally {
        if(response != null){
            try {
                response.close();
            } catch (IOException ex) {
                log.error(this.getClass(), "close response method error", ex);
            }
        }
        if(client != null){
            try {
                client.close();
            } catch (IOException ex) {
                log.error(this.getClass(), "close client method", ex);
            }
        }
    }
    return flag;
}
// get方式
public Optional<Map<String,Object>> connOrDisconnOperator(String atisAirPortCode, String url) {
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    try{
        HttpGet httpGet = new HttpGet(url + "?airportCode=" +atisAirPortCode);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(120000).build();
        httpGet.setConfig(requestConfig);
        client = HttpClients.createDefault();
        response = client.execute(httpGet);
        if(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 500){
            Map<String,Object> map = Maps.newHashMapWithExpectedSize(4);
            InputStream is = response.getEntity().getContent();
            JsonNode jn = new ObjectMapper().readTree(StringUtil.getString(is));

            // 解析返回结果
            String result = jn.get("state").asText();
            if (result.equals("SUCCESS")) {
                System.out.println("-----------------------------成功");
            } else {
                System.out.println("-----------------------------失败");
            }
            return Optional.of(map);
        }else{
            return Optional.absent();
        }
    }catch (Exception ex) {
        log.error(this.getClass(), "getOSInfo() error", ex);
        return Optional.absent();
    }finally {
        if(response != null){
            try {
                response.close();
            } catch (IOException ex) {
                log.error(this.getClass(), "close IO error", ex);
            }
        }
        if(client != null){
            try {
                client.close();
            } catch (IOException ex) {
                log.error(this.getClass(),"close IO error",ex);
            }
        }
    }
}
时间: 2024-07-30 12:07:36

HttpClient 的GET(带参数)、POST请求方式,工具类方法的相关文章

论httpclient上传带参数【commons-httpclient和apache httpclient区别】

需要做一个httpclient上传,然后啪啪啪网上找资料 1.首先以前系统中用到的了commons-httpclient上传,找了资料后一顿乱改,然后测试 PostMethod filePost = new PostMethod(url); filePost.setParameter("system", "vinuxpost"); try { Part part[] = UploadRequestHelper.getPart(request); filePost.s

httpclient发送不带参数post数据

两个问题: 1.httpclient怎样发送一个没有不论什么參数的post数据呢? 2.Webproject怎样去接收一个无參数的post呢? 起因: 今天(2014.11.10)在开发中碰到了一个问题.接口提供方提供的接口是要求使用post方式发送数据的.心想这不超简单的一个东西吗?直接post过去不就是了.可是,提供的接口是没有不论什么參数的.不是类似这样的http://api.dutycode.com/data/parm=xxx这样的接口,而是http://api.dutycode.com

python 解析ajax请求带有json参数,请求方式是post的url(注意:参数的json格式的)

import requests # tag = 'http://exercise.kingname.info/exercise_ajax_1.html'#最开始的网址,下面两个为子链接 url = 'http://exercise.kingname.info/ajax_1_backend' url2 = 'http://exercise.kingname.info/ajax_1_postbackend' req = requests.get(url) print(req.text) params

HttpClient和AsynchttpClient的get与post请求方式

HttpClient的get方式: 由于是网络请求,一定要放在子线程里做. 首先创建一个HttpClient对象: HttpClient httpClient = new DefaultHttpClient(); 然后创建一个HttpGet,将url地址传进去: HttpGet httpGet = new HttpGet(path); 然后获取状态码,200的话就是访问成功了: int code = response.getStatusLine().getStatusCode(); 接下来得到响

android使用HttpURLConnection实现带参数文件上传

文件上传是常见功能,然而android网上大多数的文件上传都使用httpclient,而且需要添加一个httpmine-jar,其实HttpURLConnection也可以实现文件上传,但是它在移动端有个弊端,就是不能上传大文件,所以这次说的方式,只能上传一些较小的文件. 文件上传,并且带上一些参数,这需要我们了解http请求的构造方式,也就是它的格式. HttpURLConnection需要我们自己构造请求头部,也就是我们要拼接出一个正确完整的请求. 下面来看一个典型的例子 POST /api

03-SpringMVC_RequestMapping_请求方式

1.标准的HTTP请求报头 2 映射请求参数.请求方式或请求头 2.1 知识点 @RequestMapping除了可以使用请求Url映射请求以外,还可以使用请求方法.请求参数及请求头映射请求 @RequestMapping的vaule.method.params及heads分别表请求URL.请求方法.请求参数及请求头的映射条件,他们之间是"与"的关系,联合使用多个条件可让请求映射更加精确化 2.2 测试method属性 2.2.1控制器类 @RequestMapping(value=&

httpclient post请求例子(无参数名与带参数名的例子)

版本:4.1 带参数名的情况 HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // httpPost.setHeader("Accept-Encoding", "gzip,deflate");//表示返回的数据是压缩的zip格式 String postParam = "";//请求的参数内容 List<NameVa

Android之Http通信——4.Android HTTP请求方式:HttpClient

本节引言: 上节讲了HttpURLConnection,本节就到HttpClient了,Apache给我们提供的HttpClient(简单的Http客户端), 不过毕竟不是亲儿子,HttpClient在API 21版本后就给Google弃用了,而我们实际开发中,很多页面都不是通过 一个简单的URL就可以访问的,可能需要登陆或者相关权限才可以访问,这就涉及到了Session,Cookie等的问题了: 当然我们可以用HttpURLConnection来实现,但是有点麻烦,而用HttpClient可以

springMVC带参数请求重定向

SpirngMVC返回逻辑视图名 可以分下面几种情况: 1. servlet进行请求转发,返回到jsp页面,如  return "index.jsp" ; 2. servlet 返回结果,让请求 重定向到某个jsp页面 ,此时servlet 返回语句类似:  return  " redirect : index.jsp "; 3. servlet 的返回结果是 请求另外一个servlet   此时servlet 返回语句类似:  return  " red