Use and encapsulation of httpclient

Source: Internet
Author: User
use and encapsulation of httpclient httpclient Introduction

The HTTP protocol is now the most widely used and important protocol on the Internet, and more and more Java applications need to access network resources directly through the HTTP protocol. HttpClient is a subproject under Apache Jakarta Common that provides an efficient, up-to-date, full-featured client-side Programming toolkit that supports HTTP protocols, and it supports the latest versions and recommendations of the HTTP protocol. HttpClient has been used in a number of projects, such as the other two famous Jakarta on the Apache Cactus and Htmlunit are using HttpClient.

There are several steps to sending a request using HttpClient:

1. Create the HttpClient object.

2. Create an instance of the request method and specify the request URL. If you need to send a GET request, create a HttpGet object, or create a HttpPost object if you need to send a POST request.

3. If you need to send request parameters, you can call the HttpGet, HttpPost Common SetParams (Hetpparamsparams) method to add request parameters, and for HttpPost objects, you can also call Setentity ( Httpentity entity) method to set request parameters.

4. Invoke the HttpClient object's execute (httpurirequestrequest) Send request, which returns a HttpResponse.

5. Call HttpResponse getallheaders (), Getheaders (String name), and so on to get the server's response header; call HttpResponse getentity () method to get the Httpentity object that wraps the response content of the server. This object is used by the program to get the response content of the server.

6. Release the connection. The connection request Web page must be released, regardless of whether the execution method succeeds

package com.cloud.day1;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.HttpException;

import Org.apache.commons.httpclient.HttpMethod;

import Org.apache.commons.httpclient.methods.GetMethod;

import Org.apache.commons.httpclient.methods.PostMethod;

/**

* Request Web page based on HTTP protocol

*/

Public class Demo1 {

Public static void main (string[] args) throws HttpException, IOException {

Request to create a client

HttpClient client = new httpclient ();

Create a GET request

HttpMethod method = new getmethod ("http://www.baidu.com");

Create a POST request

HttpMethod method2 = new postmethod ("http://www.baidu.com");

Client Send Request

Client.executemethod (method);

Client.executemethod (METHOD2);

System.out.println ("--------------GET Request returns information----------");

System.out.println ("Get:" +method.getstatusline ());

System.out.println ("Get:" +method.getresponsebodyasstring ());

System.out.println ("--------------POST request return information---------");

System.out.println ("Post:" +method2.getstatusline ());

System.out.println ("Post:" +method2.getresponsebodyasstring ());

Release connection

Method.releaseconnection ();

Method2.releaseconnection ();

}

}

Download Network Pictures

package com.cloud.day1;

import java.io.File;

import Java.io.FileOutputStream;

import Java.io.InputStream;

import Java.text.SimpleDateFormat;

import java.util.Date;

import org.apache.commons.httpclient.HttpClient;

import Org.apache.commons.httpclient.methods.GetMethod;

/**

* Download pictures from the internet according to the URL of the image

*/

Public class Demo2 {

Public static void main (string[] args) {

Downimage ("http://d.3987.com/lmxj_130510/005.jpg");

}

Public static void downimage (String posturl) {

HttpClient client = new httpclient ();

GetMethod GetMethod = new getmethod (PostURL);

FileOutputStream Fos;

Try {

Client.executemethod (GetMethod);

String name = new simpledateformat ("YyyyMMdd hhmmss"). Format (new Date ());

File outfile = new file ("e:/" +name+ ". jpg");

FOS = new fileoutputstream (outfile);

InputStream InputStream = Getmethod.getresponsebodyasstream ();

byte [] b = new byte[1024];

int len = 0;

while ((Len=inputstream.read (b))!=-1) {

Fos.write (B,0,len);

}

Inputstream.close ();

Fos.close ();

Catch(Exception e) {

E.printstacktrace ();

finally{

Getmethod.releaseconnection ();

}

}

}

Impersonate User Login

package com.cloud.day1;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.HttpException;

import Org.apache.commons.httpclient.NameValuePair;

import Org.apache.commons.httpclient.methods.PostMethod;

import org.apache.commons.httpclient.params.HttpClientParams;

/**

* Post mode submit form, simulate user's login request

*/

Public class Demo3 {

Public static void main (string[] args) throws HttpException, IOException {

Postform ();

}

Public static void postform () throws HttpException, ioexception{

HttpClient httpclient = new httpclient ();

Postmethod Postmethod = new postmethod ("http://localhost:8080/QuartzTest/getData/login.do");

String userName = "Spring";

String PassWord = "123";

Httpclientparams params = new httpclientparams ();

Params.setsotimeout (30000);

Httpclient.setparams (params);

Namevaluepair uname = new namevaluepair (UserName, userName);

Namevaluepair Pword = new namevaluepair (PassWord, PassWord);

namevaluepair[] data = {Uname,pword};

Postmethod.setrequestbody (data);

Httpclient.executemethod (Postmethod);

System.out.println (Postmethod.getresponsebodyasstring ());

}

}

Query number Attribution Place

package com.cloud.day1;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.HttpException;

import Org.apache.commons.httpclient.HttpMethod;

import Org.apache.commons.httpclient.NameValuePair;

import Org.apache.commons.httpclient.methods.GetMethod;

import Org.apache.commons.httpclient.methods.PostMethod;

/**

* According to the POST request, the place where the query number belongs

*/

Public class Demo4 {

/**

* @param args

* @throws HttpException

* @throws IOException

*/

Public static void main (string[] args) throws HttpException, IOException {

HttpClient httpclient = new httpclient ();

Httpclient.gethostconfiguration (). Sethost ("www.114best.com", "n", "http");

HttpMethod method = Postmethod ();

Httpclient.executemethod (method);

System.out.println ("1:" +method.getstatusline ());

String response = new string (method.getresponsebodyasstring ());

System.out.println ("2:" +response);

Method.releaseconnection ();

}

/**

* Data submitted by Get method

* @return HttpMethod

*/

@SuppressWarnings ("unused")

private static HttpMethod GetMethod () {

return New GetMethod ("/simcard.php?simcard=1330227");

}

/**

* Submit data using POST method

* @return HttpMethod

*/

private static HttpMethod Postmethod () {

Here according to the URL above stitching query parameters

Postmethod post = new postmethod ("/dh/114.aspx");

Namevaluepair w = new namevaluepair ("W", "18225896837");

Post.setrequestbody (new namevaluepair[]{w});

return post;

}

}

encapsulation httpclient in Java system

package com.cloud.day1;

import Java.util.Map;

import org.apache.commons.httpclient.HttpClient;

import Org.apache.commons.httpclient.NameValuePair;

import Org.apache.commons.httpclient.methods.PostMethod;

import org.apache.commons.httpclient.params.HttpMethodParams;

/**

* The HttpClient function is encapsulated

* Send request, return request result

*/

Public class Demo5 {

}

class apppostrequest{

Request parameters

Public Map<string, string> params;

Request URL

Public String URL;

Time format

Public String Dataformart = "Yyyy-mm-dd HH:mm:ss";

Connection Timeout

public int connectiontimeout = 6000;

Read timeout

public int readtimeout = 3000;

//

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.