基于httpclient解析http请求

上一篇 / 下一篇  2018-03-22 11:43:39

public static void main(String[] args) {   
        // 创建默认的httpClient实例.     
        CloseableHttpClient httpclient = HttpClients.createDefault();   
        // 创建httppost     
        HttpPost httppost = new HttpPost(URL);   
        // 创建参数队列     
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
            //设置请求参数
        formparams.add(new BasicNameValuePair("userName", userName)); 
        formparams.add(new BasicNameValuePair("password", password));
        formparams.add(new BasicNameValuePair("pwd",pwd ));
        formparams.add(new BasicNameValuePair("encrypt", encrypt));
        
        UrlEncodedFormEntity uefEntity;   
        try {   
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); 
            
//             调用setParams、setEntity设置请求参数
            httppost.setEntity(uefEntity);   
            System.out.println("executing request " + httppost.getURI());
//             发送请求,接受响应
            CloseableHttpResponse response = httpclient.execute(httppost);   
            System.out.println("响应行和响应头"+response.toString());
            try {   
//             获取响应的响应体
                HttpEntity entity = response.getEntity();   
                if (entity != null) {   
                    JSONObject json = JSONObject.fromObject(EntityUtils.toString(entity, "UTF-8"));
                    String result = json.getString("result"); 
                    String msg = json.getString("msg"); 
                    System.out.println("result:"+result);
                    System.out.println("msg:"+msg);
                }   
            } finally {   
                response.close();   
            }   
        } catch (ClientProtocolException e) {   
            e.printStackTrace();   
        } catch (UnsupportedEncodingException e1) {   
            e1.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        } finally {   
            // 关闭连接,释放资源     
            try {   
                httpclient.close();   
            } catch (IOException e) {   
                e.printStackTrace();   
            }   
        }   
    }   


}

TAG:

 

评分:0

我来说两句

日历

« 2024-04-14  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 2743
  • 日志数: 4
  • 建立时间: 2017-07-24
  • 更新时间: 2018-07-16

RSS订阅

Open Toolbar