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

时间:2015-08-26 17:05:11   收藏:0   阅读:444

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

 

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

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!