HTTP Post Request using Apache Commons

Demonstrates an HTTP Post using the Apache Commons HTTP library.

Required Libraries:

Example Source Code

 1  import java.io.IOException;

 2 import java.io.InputStream;

 3 import java.util.ArrayList;

 4 import java.util.List;

 5 

 6 import org.apache.commons.io.IOUtils;

 7 import org.apache.http.HttpEntity;

 8 import org.apache.http.HttpResponse;

 9 import org.apache.http.client.ClientProtocolException;

10 import org.apache.http.client.HttpClient;

11 import org.apache.http.client.entity.UrlEncodedFormEntity;

12 import org.apache.http.client.methods.HttpPost;

13 import org.apache.http.impl.client.DefaultHttpClient;

14 import org.apache.http.message.BasicNameValuePair;

15 

16 public class ExampleHttpPost

17 {

18   public static void main(String args[]) throws ClientProtocolException, IOException

19   {

20     HttpPost httppost = new HttpPost("https://stanfordwho.stanford.edu/SWApp/Search.do");

21 

22     List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();

23     parameters.add(new BasicNameValuePair("search", "jsproch"));

24     parameters.add(new BasicNameValuePair("filters", "closed"));

25     parameters.add(new BasicNameValuePair("affilfilter", "everyone"));

26     parameters.add(new BasicNameValuePair("btnG", "Search"));

27     

28     httppost.setEntity(new UrlEncodedFormEntity(parameters));

29 

30     HttpClient httpclient = new DefaultHttpClient();

31     HttpResponse httpResponse = httpclient.execute(httppost);

32     HttpEntity resEntity = httpResponse.getEntity();

33     

34     // Get the HTTP Status Code

35     int statusCode = httpResponse.getStatusLine().getStatusCode();

36 

37     // Get the contents of the response

38     InputStream input = resEntity.getContent();

39     String responseBody = IOUtils.toString(input);

40     input.close();

41     

42     // Print the response code and message body

43     System.out.println("HTTP Status Code: "+statusCode);

44     System.out.println(responseBody);

45   }

46 } 
View Code

 

你可能感兴趣的:(apache commons)