使用HttpClient访问网络

HttpClient的HttpGet和HttpPost访问网络

核心代码:

HttpClient
apache 发布,模拟一个浏览器 
步骤:

1.打开浏览器
HttpClient client = new DefaultHttpClient()
2.输入一些内容
HttpGet
3.敲回车
client.execute(path); 

1、HttpGet

/**
 * 1、使用HttpClient——GET方式进行登录
 * 
 * @throws IOException
 */
public static String loginByGet(String username, String password)throws IOException {

    System.out.println("以GET方式提交。。。");
    // 1、打开一个浏览器
    HttpClient client = new DefaultHttpClient();


    String path = "http://192.168.221.221:8080/web/LoginServlet?username="
            + username + "&password" + password;
    // 2、输入url地址
    HttpGet httpGet = new HttpGet(path);


    // 3、敲回车
    HttpResponse response = client.execute(httpGet);


    int code = response.getStatusLine().getStatusCode();
    if (code == 200) {
        // 数据实体
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        String text = StreamUtils.readStream(in);
        return text;
    }
    return null;
} 

2、HttpPost

    /**
 * 2、使用HttpClient——POST方式登录
 * 
 * @param username
 * @param password
 * @return
 * @throws IOException
 */
public static String loginByPost(String username, String password)
        throws IOException {
    System.out.println("以POST方式登录。。。");


    String path = "http://192.168.221.221:8080/web/LoginServlet";
    // 1、打开一个浏览器


    HttpClient client = new DefaultHttpClient();
    // 2、输入url地址


    HttpPost httpPost = new HttpPost(path);


    // 3、设置请求内容
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("username", username));
    parameters.add(new BasicNameValuePair("password", password));
    HttpEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
    // 对请求参数进行编码:encoding the name/value pairs be encoded with
    httpPost.setEntity(entity);

    // 4、敲回车
    HttpResponse response = client.execute(httpPost);
    int code = response.getStatusLine().getStatusCode(); // 服务器状态码
    if (code == 200) {
        //把封装在返回体中的数据取出来
        InputStream in = response.getEntity().getContent();
        String text = StreamUtils.readStream(in);
        return text;
    }
    return null;
}  

注意事项

  1. get方式访问网络的时候的参数还是要组合到url地址后面的
  2. 不管get请求还是post请求返回来的数据都封装在HttpResponse对象中,然后通过这个方法的一系列 getXXX方法获取你想要的内容

使用到的重要api

  1. new DefaultHttpClient();获取一个HttpClient对象
  2. new HttpGet(path);//获得一个Httpget对象
  3. new HttpPost(path)//获得一个HttpPost对象
  4. client.execute(httpGet);//把get请求或者post请求提交到服务器,返回结果集
  5. setEntity(entity);使用post请求方式的时候用来设置请求体的数据的方法
  6. response.getStatusLine().getStatusCode(); //通过状态行对象来拿到服务器状态码
  7. response.getEntity().getContent();//通过返回体对象获取服务器返回的数据流对象
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值