2.使用org.apache.http.client.HttpClient访问网络

一个是操作类,一个是junit test类,直接上代码:

org.apache.http.client.HttpClient.java

package org.example.httpclient;

import java.util.ArrayList;
import java.util.List;

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

public class MHttpClient {

    public void get() throws Exception {
        // 创建HttpClient实例
        HttpClient client = new DefaultHttpClient();
        // 根据URL创建HttpGet实例
        HttpGet get = new HttpGet("http://192.168.1.132:8088/WebServer/student.do");
        // 执行get请求,得到返回体
        HttpResponse response = client.execute(get);
        // 判断是否正常返回
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 解析数据
            String data = EntityUtils.toString(response.getEntity());
            System.out.println(data);
        }
    }

    public void post() throws Exception {
        // 创建HttpClient实例
        HttpClient client = new DefaultHttpClient();
        // 根据URL创建HttpPost实例
        HttpPost post = new HttpPost("http://192.168.1.132:8088/WebServer/student.do");
        // 构造post参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", "11"));
        // 编码格式转换
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
        // 传入请求体
        post.setEntity(entity);
        // 发送请求,得到响应体
        HttpResponse response = client.execute(post);
        // 判断是否正常返回
        if (response.getStatusLine().getStatusCode() == 200) {
            // 解析数据
            HttpEntity resEntity = response.getEntity();
            String data = EntityUtils.toString(resEntity);
            System.out.println(data);
        }
    }

}


MHttpClientTestCast.java

package org.example.httpclient;

import android.test.AndroidTestCase;

public class MHttpClientTestCast extends AndroidTestCase {

    public void testGet() throws Exception {
        MHttpClient client = new MHttpClient();
        client.get();
    }

    public void testPost() throws Exception {
        MHttpClient client = new MHttpClient();
        client.post();
    }

}


和URL对比了一下,感觉就是封装了底层的流操作


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值