Org.apache.http.client.HttpClient Get/post Request

Source: Internet
Author: User

Request Step

1. Create a HttpClient object

2, create the request method, the value of the constructor is the request path

3. Call the Execute () method of the object in 1, object with parameter 2

4. Get Request response data

5. Release the connection resources

6. Processing data

One, using the org.apache.http.client.HttpClient GET request to implement

1, request the core code:

Create a HttpClient object
HttpClient HttpClient = new Defaulthttpclient ();
Create request mode because it is a GET request, so you can connect request parameters after the URL
HttpGet httpget= New HttpGet ("Http://localhost:8080/music/user/delete.do?id=110&name=name");
try{
Execute request, get response data
HttpResponse response = Httpclient.execute (HttpGet);
Gets the request entity,
httpentity entity = response.getentity ();
Gets the length of the contents of the returned instance
Long len= entity.getcontentlength ();
Get content Type
Header head= Entity.getcontenttype ();
String bodys= head.tostring ();
System.out.println ("Content Length" +len + "head content" +bodys);
Getting the instance stream
if (Entity! = null) {
InputStream input= entity.getcontent ();
byte []buffer= new byte[2048];
Input.read (buffer);
String body= new string (buffer, "utf-8");
SYSTEM.OUT.PRINTLN ("Access to resources" +body);
Jsonobject json= new Jsonobject ();
Json=jsonobject.fromobject (body);
String ids= json.getstring ("id");
String names=json.getstring ("name");
System.out.print (IDS);
System.out.print (names);
}
}catch (HttpException e) {
E.printstacktrace ();
}catch (IOException ee) {
Ee.printstacktrace ();
}finally{
Httpget.releaseconnection ();
}

2. Server-side response request Core code:

Request full path url=http://localhost:8080/music/user/delete.do?

@RequestMapping (value= "/delete.do")
public void Delete (String id,string name,httpservletresponse response) {
SYSTEM.OUT.PRINTLN ("Request to reach Delete");
String yid= ID;
String Yname=name;
SYSTEM.OUT.PRINTLN ("Request Parameters" +yid);
SYSTEM.OUT.PRINTLN ("Request parameter name:" +name);
try {
OutputStream output= Response.getoutputstream ();

Encoding settings
Response.setcharacterencoding ("UTF-8");

Settings for theme types
Response.setcontenttype ("text/html");
This passes a JSON-formatted data
Jsonobject json= new Jsonobject ();
Json.put ("id", 10);
Json.put ("name", "name");
String jstring= json.tostring ();

Encoding settings
byte [] b= jstring.getbytes ("UTF-8");

Response Data output
Output.write (b);
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

Second, using the Org.apache.http.client.HttpClient GET request to implement, self-patchwork URL and multiple request data

1. Request to send core code

Create HttpClient objects use httpclient here
HttpClient HttpClient = new Defaulthttpclient ();
Create a Request Method object
HttpGet httpget = new HttpGet ();
try{
Request the creation of parameter objects and setting of parameters
list<namevaluepair> qparams = new arraylist<namevaluepair> ();
Qparams.add (New Basicnamevaluepair ("id", "110110"));
Qparams.add (New Basicnamevaluepair ("name", "you Name"));
Qparams.add (New Basicnamevaluepair ("Age", "10"));
Qparams.add (New Basicnamevaluepair ("Sex", "man"));
The assembly of the URL, and the setting of the request parameter encoding
Java.net.URI URI = Uriutils.createuri ("http", "Localhost:8080/music/user",-1, "/delete.do",
Urlencodedutils.format (Qparams, "UTF-8"), null);
Set a value for the request path, according to the access path
Httpget.seturi (URI);
System.out.println (Httpget.geturi ());
Execute request, get response data
HttpResponse response = Httpclient.execute (HttpGet);
Gets the request entity,
httpentity entity = response.getentity ();
Gets the length of the contents of the returned instance
Long len= entity.getcontentlength ();
Get content Type
Header head= Entity.getcontenttype ();
String bodys= head.tostring ();
System.out.println ("Content length:" +len + "head content:" +bodys);
Getting the instance stream
if (Entity! = null) {
InputStream input= entity.getcontent ();
byte []buffer= new byte[2048];
Input.read (buffer);
String body= new string (buffer, "utf-8");
SYSTEM.OUT.PRINTLN ("Access to resources" +body);
Jsonobject json= new Jsonobject ();
Json=jsonobject.fromobject (body);
String ids= json.getstring ("id");
String names=json.getstring ("name");
System.out.print (IDS);
System.out.print (names);
}
}catch (HttpException e) {
E.printstacktrace ();
}catch (IOException ee) {
Ee.printstacktrace ();
}catch (Exception eee) {
Eee.printstacktrace ();
}finally{
Httpget.releaseconnection ();
}


2, receive the request, respond to the request core code

Request full path: url=http://localhost:8080/music/user/delete.do

@RequestMapping (value= "/delete.do")
public void Delete (String id,string name,httpservletresponse response) {
SYSTEM.OUT.PRINTLN ("Request to reach Delete");
String yid= ID;
String Yname=name;
SYSTEM.OUT.PRINTLN ("Request Parameters" +yid);
SYSTEM.OUT.PRINTLN ("Request parameter name:" +name);
try {
OutputStream output= Response.getoutputstream ();

        //settings for Output content encoding
         Response.setcharacterencoding ("UTF-8");
        response.setcontenttype ("text/html");
        //here to pass a JSON format data
        jsonobject   json= new Jsonobject ();
        json.put ("id", 10);
        json.put ("name", "name");
        string jstring= json.tostring ();

Encoding settings
byte [] b= jstring.getbytes ("UTF-8");
Output.write (b);
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}


Third, using the Org.apache.http.client.HttpClient POST request to implement

1. Request-Side Core code

Create HttpClient objects use httpclient here
HttpClient HttpClient = new Defaulthttpclient ();
Assembly of Request parameters
list<namevaluepair> qparams = new arraylist<namevaluepair> ();
Qparams.add (New Basicnamevaluepair ("id", "110110"));
Qparams.add (New Basicnamevaluepair ("name", "you Name"));
Qparams.add (New Basicnamevaluepair ("Age", "10"));
Qparams.add (New Basicnamevaluepair ("Sex", "man"));
try{

urlencodedformentity instances will use URL encoding to encode parameters

urlencodedformentity entity = new Urlencodedformentity (qparams, "UTF-8");
HttpPost httppost= New HttpPost ("http://localhost:8080/music/user/delete.do");
Settings for Request parameters
Httppost.setentity (entity);
Request execution, and access to the response data
HttpResponse response = Httpclient.execute (HttpPost);

GET Request Response
Httpentity Entitys = response.getentity ();

Length of response content
Long len= entity.getcontentlength ();

Types of response content
Header head= Entity.getcontenttype ();
String bodys= head.tostring ();
System.out.println ("Content length:" +len + "head content:" +bodys);
if (entitys! = null) {

Get Response data
InputStream input= entitys.getcontent ();
byte []buffer= new byte[2048];
Input.read (buffer);

Encoding settings
String body= new string (buffer, "utf-8");
SYSTEM.OUT.PRINTLN ("Access to resources" +body);
}
}catch (Exception e) {
E.printstacktrace ();
}

2, receive the request, respond to the request core code

Request full path: url=http://localhost:8080/music/user/delete.do

@RequestMapping (value= "/delete.do")
Public void  Delete (String id,string name,string age, HttpServletResponse response) {
    system.out.println ("Request arrival delete");
    string yid= ID;
    string Yname=name;
    string ages=age;
    system.out.println ("Request Parameters" +yid);
    system.out.println ("Request parameter name:" +name);
    system.out.println ("Request parameter Age:" +ages);
    try {
        outputstream output= response.getoutputstream ( );

Settings for response content encoding
Response.setcharacterencoding ("UTF-8");
Response.setcontenttype ("text/html");
This passes a JSON-formatted data
Jsonobject json= new Jsonobject ();
Json.put ("id", 10);
Json.put ("name", "name");
String jstring= json.tostring ();
byte [] b= jstring.getbytes ("UTF-8");
Output.write (b);
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

Org.apache.http.client.HttpClient Get/post Request

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.