码迷,mamicode.com
首页 > 编程语言 > 详细

java使用HttpURLConnection和HttpClient分别模拟get和post请求以及操作cookies

时间:2015-08-26 17:05:41      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:

1.使用HttpURLConnection

   
    public static String getJsonByURL(String base_url) {
        String url = base_url;
        StringBuilder json = new StringBuilder();    
        String result = "";
        
            try {
                URL u = new URL(url);
                HttpURLConnection uc = (HttpURLConnection) u.openConnection();
                uc.setRequestMethod("GET");
                //uc.setRequestMethod("POST");
                /*
                String cookieVal =uc.getHeaderField("Set-Cookie");    //获取session        
                String JSESSIONID = (cookieVal.substring(0,cookieVal.indexOf(";")));
                uc.setRequestProperty("Cookie", JSESSIONID);//设置session
                */
                BufferedReader bd = new BufferedReader(new InputStreamReader(uc.getInputStream(),"GBK"));
                String s = null;
                while((s=bd.readLine())!=null) {
                    json.append(s);
                }
                bd.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            result = json.toString();
            
    
        return result;
    }

2.使用HttpClient

(1)get

    public static String getJsonByGet(String url) {
        String s = "";
        //CloseableHttpClient httpclient = HttpClients.createDefault(); 
        DefaultHttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());
         HttpGet httpget = new HttpGet(url);  
         CloseableHttpResponse response = null;  
         HttpEntity entity = null;
         try {
            response = httpclient.execute(httpget);
            entity = response.getEntity(); 
            /*            
            CookieStore cookieStore = httpclient.getCookieStore();//获取cookies
            httpclient.setCookieStore(cookieStore);//设置cookies
            */
            s = EntityUtils.toString(entity, "UTF-8");
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            httpclient.close();
        }        
         return s;
    }
    

(POST)

   public static String getJsonByPost(String url) {  
        
        DefaultHttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager()); 
        //CloseableHttpClient httpclient = HttpClients.createDefault();   
        HttpPost httppost = new HttpPost(url);  
         
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String s = "";
        try {
            response = httpclient.execute(httppost);
            entity = response.getEntity();
            s = EntityUtils.toString(entity, "UTF-8");
        } catch (ClientProtocolException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            
        }finally {
            httpclient.close();
        }
        return s;
    } 

获取cookies和设置cookies的位置要根据不同的接口而定。

以上的方法是把接口的参数,在调用方法之前就配好了,作为url传入。也可在调用的相应方法内部做处理。

1.使用HttpURLConnection

    public static byte[] getJsonByURL(String url, String params) throws Exception{
        URL url = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");// 
        // conn.setConnectTimeout(10000);//
        // conn.setReadTimeout(2000);//
        conn.setDoOutput(true);// 
        byte[] bypes = params.toString().getBytes();
        conn.getOutputStream().write(bypes);// 输入参数
        InputStream inStream=conn.getInputStream();
        return StreamTool.readInputStream(inStream);
    }

对参数的处理有很多方法,可以append(),也可以自己+,不同参数,不同方法重载

2.使用HttpClient

 

java使用HttpURLConnection和HttpClient分别模拟get和post请求以及操作cookies

标签:

原文地址:http://www.cnblogs.com/qiaoyeye/p/4741579.html

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