用HttpClient模拟HTTP的GET和POST请求

一、HttpClient介绍

 

HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器

HTTP GET核心代码:

(1)DefaultHttpClient client = new DefaultHttpClient();

(2)HttpGet get = new HttpGet(String url);//此处的URL为http://..../path?arg1=value&....argn=value

(3)HttpResponse response = client.execute(get); //模拟请求

(4)int code = response.getStatusLine().getStatusCode();//返回响应码

(5)InputStream in = response.getEntity().getContent();//服务器返回的数据

 

HTTP POST核心代码:

(1)DefaultHttpClient client = new DefaultHttpClient();

(2)BasicNameValuePair pair = new BasicNameValuePair(String name,String value);//创建一个请求头的字段,比如content-type,text/plain

(3)UrlEncodedFormEntity entity = new UrlEncodedFormEntity(List<NameValuePair> list,String encoding);//对自定义请求头进行URL编码

(4)HttpPost post = new HttpPost(String url);//此处的URL为http://..../path

(5)post.setEntity(entity);

(6)HttpResponse response = client.execute(post);

(7)int code = response.getStatusLine().getStatusCode();

(8)InputStream in = response.getEntity().getContent();//服务器返回的数据

 

//测试代码:

public static void main(String[] args) throws Exception

    {

        DefaultHttpClient client = new DefaultHttpClient();

        List<NameValuePair> list = new ArrayList<NameValuePair>();

        

        String data = "aaa";

        NameValuePair pair1 = new BasicNameValuePair("data", data);

        list.add(pair1);

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");

        HttpPost post = new HttpPost("http://192.168.0.10:80/Server/Servlet/");

        post.setEntity(entity);

        HttpResponse response = client.execute(post);

        if(response.getStatusLine().getStatusCode() == 200)

        {

            InputStream in = response.getEntity().getContent();// 接收服务器的数据

            String str = readString(in);

            System.out.println("str:" + str);

        }

        else

        {

            System.out.println("调用失败");

        }

    }

    

    private static String readString(InputStream in) throws Exception

    {

        byte[] data = new byte[1024];

        int length = 0;

        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        while((length = in.read(data)) != -1)

        {

            bout.write(data, 0, length);

        }

        return new String(bout.toByteArray(), "UTF-8");

        

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值