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

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

 

复制代码
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也可以使用下面的方式:

复制代码
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(); } } }
复制代码

 

posted on   乔叶叶  阅读(13216)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示