java使用HttpURLConnection和HttpClient分別模擬get和post請求以及操做cookies

1.使用HttpURLConnectionjava

   
    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.使用HttpClientapache

(1)getjson

    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)cookie

   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的位置要根據不一樣的接口而定。session

以上的方法是把接口的參數,在調用方法以前就配好了,做爲url傳入。也可在調用的相應方法內部作處理。app

1.使用HttpURLConnectionpost

    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(),也能夠本身+,不一樣參數,不一樣方法重載ui

2.使用HttpClient編碼

 

package com.tradeyun;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/** 
 * @author QiaoJiafei 
 * @version 建立時間:2015年12月18日 上午10:03:12 
 * 類說明 
 */
public class TestHttpClientParameter {
    public static void main(String args[]) {
/*        HttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());
        String s = "";
        HttpResponse response = null;
        HttpEntity entity = null;
        String url = "http://172.16.30.244:8090/gm_product_site/assignmentApply/auth";
        System.out.println("url=========="+url);
        HttpPost post = new HttpPost(url);
        List formparams = new ArrayList();
        formparams.add(new BasicNameValuePair("applyId","1"));
        formparams.add(new BasicNameValuePair("isPass","true"));
        //formparams.add(new BasicNameValuePair("pwd","aaaaaa1"));
        //formparams.add(new BasicNameValuePair("pwd", "aaaaaa1"));  
        UrlEncodedFormEntity uefEntity;
        try {
             uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
             
             post.setEntity(uefEntity);  
             System.out.println("executing request " + post.getURI());  
             response = httpclient.execute(post);
             entity = response.getEntity();
             s= EntityUtils.toString(entity, "UTF-8");  
             System.out.println(s);
             
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } */ //不成功
        TestHttpClientParameter t = new TestHttpClientParameter();
        t.post3();
    }
    
    public void post3() {
        HttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());
        String s = "";
        HttpResponse response = null;
        HttpEntity entity = null;
        String url = "http://172.16.30.244:8090/gm_product_site/assignmentApply/auth";
        System.out.println("url=========="+url);
        HttpPost post = null;
        List formparams = new ArrayList();
        formparams.add(new BasicNameValuePair("applyId","1"));
        formparams.add(new BasicNameValuePair("isPass","true"));
 
        UrlEncodedFormEntity uefEntity;
        try {
             uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
             

             URI uri=null;
                try {
                    uri = URIUtils.createURI("http", "172.16.30.244:8090", -1, "/gm_product_site/assignmentApply/auth",
                    URLEncodedUtils.format(formparams, "UTF-8"), null);
                } catch (URISyntaxException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                post = new HttpPost(uri);
                System.out.println(post.getURI());
             response = httpclient.execute(post);
             entity = response.getEntity();
             s= EntityUtils.toString(entity, "UTF-8");  
             System.out.println(s);
             
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

httpclient也能夠使用下面的方式:url

package com.core.execute;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/** 
 * @author QiaoJiafei 
 * @version 建立時間:2016年3月2日 上午10:54:24 
 * 類說明 
 */
public class TestMapPara {
    static HttpClient client = HttpClients.createDefault();
    
    public static void main(String args[]) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", "22");
        postmap(map);
    }

    private static void postmap(Map<String, String> params) {
        // TODO Auto-generated method stub
        String url = "http://172.16.30.73:8080/test/user/update";
        HttpPost httppost = new HttpPost(url);
        List<NameValuePair> ps = new ArrayList<NameValuePair>();
        for (String pKey : params.keySet()) {
            ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
        }
        try {
            httppost.setEntity(new UrlEncodedFormEntity(ps));
       //上面一行代碼也能夠使用帶有編碼格式的構造方法,如new UrlEncodedFormEntity(ps, "UTF-8"); HttpResponse response
= client.execute(httppost); HttpEntity httpEntity = response.getEntity(); System.out.println(EntityUtils.toString(httpEntity,"utf-8")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
相關文章
相關標籤/搜索