温习HttpClient使用范例

Apache HttpClient - Tutorial

Lars Vogel

Version 1.2

23.08.2012

Revision History
Revision 0.1 03.10.2008 Lars
Vogel
First Version
Revision 0.2 - 1.2 01.05.2009 - 23.08.2012 Lars
Vogel
bug fixes and enhancements

Apache HttpClient

This tutorial describes how to use the Apache HttpClient library for accessing HTTP resources. This tutorial is based on Apache HttpClient 4.1.


1. Using the Apache HttpClient

The Apache HttpClient library simplifies handling HTTP requests. To use this library download the binaries with dependencies from http://hc.apache.org/ and add then to your project class path.

You retrieve and send data via the HttpClient class. An instance of this class can be created with new DefaultHttpClient();

DefaultHttpClient is the standard HttpClient and uses the SingleClientConnManager class to handle HTTP connections. SingleClientConnManager is not thread-safe, this means that access to it via several threads will create problems.

The HttpClient uses a HttpUriRequest to send and receive data. Important subclass ofHttpUriRequest are HttpGet and HttpPost. You can get the response of the HttpClient as an InputStream.

2. Examples

2.1. Project and Expectations

The following examples do not necessary work out of the box as we do not provide the required backend for receiving the data. Think of the following as examples how to setup HttpClients. Download the HttpClient libraries from the Apache Website, you can download the "bin" package it includes all dependencies.

Create a new Java project de.vogella.web.httpclient, and add them to the path of your Java project. We use the project for creating our tests.

2.2. Http Get

The following is an example an HTTP Get request via HttpClient.

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.vogella.com");
HttpResponse response = client.execute(request);

// Get the response
BufferedReader rd = new BufferedReader
  (new InputStreamReader(response.getEntity().getContent()));
    
String line = "";
while ((line = rd.readLine()) != null) {
  textView.append(line);
} 

2.3. Http Post

The following will send a post request to the URL "http://vogellac2dm.appspot.com/register" and include a parameter "registrationid" which an random value.

package de.vogella.web.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

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.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class SimpleHttpPut { 
  public static void main(String[] args) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://vogellac2dm.appspot.com/register");
    try {
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
      nameValuePairs.add(new BasicNameValuePair("registrationid",
          "123456789"));
      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 
      HttpResponse response = client.execute(post);
      BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      String line = "";
      while ((line = rd.readLine()) != null) {
        System.out.println(line);
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
} 

The following request adds several parameters to the post request.

package de.vogella.web.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

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.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class TestHttpClient {
  public static void main(String[] args) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");

    try {

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
      nameValuePairs.add(new BasicNameValuePair("Email", "youremail"));
      nameValuePairs
          .add(new BasicNameValuePair("Passwd", "yourpassword"));
      nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
      nameValuePairs.add(new BasicNameValuePair("source",
          "Google-cURL-Example"));
      nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));

      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      HttpResponse response = client.execute(post);
      BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

      String line = "";
      while ((line = rd.readLine()) != null) {
        System.out.println(line);
        if (line.startsWith("Auth=")) {
          String key = line.substring(5);
          // Do something with the key
        }

      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
} 
from: http://blog.csdn.net/yorkcai/article/details/8333695
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值