I. Introduction of HttpClient
HttpClient is used to simulate HTTP requests, in essence, the HTTP request is simulated and sent to the Web server;
Android has integrated the httpclient, so it can be used directly;
Note: Here HttpClient code can not only apply to Android, but also to the General Java program;
HTTP GET Core code:
(1) Defaulthttpclient client = new Defaulthttpclient ();
(2) httpget get = new HttpGet (String URL);//The URL here is http://..../path?arg1=value&....argn=value
(3) HttpResponse response = Client.execute (get); Impersonation Request
(4) Int code = Response.getstatusline(). Getstatuscode ();// Return Response code
(5) inputstream in = Response.getEntity(). getcontent ();// data returned by the server
HTTP POST Core code:
(1) Defaulthttpclient client = new Defaulthttpclient ();
(2) Basicnamevaluepair pair = new Basicnamevaluepair (String name,string value);//Create a field for the request header , Like Content-type,text/plain.
(3) urlencodedformentity entity = new Urlencodedformentity (list<namevaluepair> list,string encoding);// URL encoding of a custom request header
(4) HttpPost post = new HttpPost (String URL);//The URL here is Http://..../path
(5) post.setentity (entity);
(6) HttpResponse response = Client.execute (POST);
(7) Int code = Response.getstatusline (). Getstatuscode (); Return Response Code
(8) InputStream in = Response.getentity (). getcontent ();//data returned by the server
Join in Androidmanifest.xml:
<android:name= "Android.permission.INTERNET"/>
Second, server-side code
The server-side code and the code that makes the request through URLConnection are the same:
PackageOrg.xiazdong.servlet; Importjava.io.IOException; ImportJava.io.OutputStream; Importjavax.servlet.ServletException; ImportJavax.servlet.annotation.WebServlet; ImportJavax.servlet.http.HttpServlet; Importjavax.servlet.http.HttpServletRequest; ImportJavax.servlet.http.HttpServletResponse; @WebServlet ("/servlet1") Public classServlet1extendsHttpServlet {protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {String nameparameter= Request.getparameter ("name"); String Ageparameter= Request.getparameter ("Age"); String name=NewString (Nameparameter.getbytes ("iso-8859-1"), "UTF-8"); String Age=NewString (Ageparameter.getbytes ("iso-8859-1"), "UTF-8"); System.out.println ("GET"); System.out.println ("Name=" +name); System.out.println ("Age=" +Age ); Response.setcharacterencoding ("UTF-8"); OutputStream out= Response.getoutputstream ();//Return DataOut.write ("GET request succeeded!". GetBytes ("UTF-8")); Out.close (); } protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {request.setcharacterencoding ("UTF-8"); String name= Request.getparameter ("name"); String Age= Request.getparameter ("Age"); System.out.println ("POST"); System.out.println ("Name=" +name); System.out.println ("Age=" +Age ); Response.setcharacterencoding ("UTF-8"); OutputStream out=Response.getoutputstream (); Out.write ("POST request succeeded!". GetBytes ("UTF-8")); Out.close (); } }
Third, the Android client code
The effect is as follows:
Join in Androidmanifest.xml:
[HTML] < uses-permission android:name= "Android.permission.INTERNET"/>
Mainactivity.java
[java] Package org.xiazdong.network.httpclient; Import java.io.bytearrayoutputstream; Import java.io.ioexception; Import java.io.inputstream; import java.net.urlencoder; Import java.util.arraylist; Import java.util.list; Import org.apache.http.httpresponse; Import org.apache.http.namevaluepair; Import org.apache.http.client.entity.urlencodedformentity; Import org.apache.http.client.methods.httpget; Import org.apache.http.client.methods.httppost; Import org.apache.http.impl.client.defaulthttpclient; Import org.apache.http.message.basicnamevaluepair; Import android.app.activity; Import android.os.bundle; import android.view.view; Import android.view.view.onclicklistener; Import android.widget.button; Import android.widget.edittext; Import android.widget.toast;
public class Mainactivity extends Activity {
Private EditText name, age;
Private Button Getbutton, Postbutton;
Private Onclicklistener listener = new Onclicklistener () {
@Override
public void OnClick (View v) {
try{
if (postbutton==v) {
/* * Namevaluepair represents a header,list<namevaluepair> store all header fields * Urlencodedformentity URL encoding similar to urlencoder statement * HttpPost POST request similar to HTTP * Client.execute () Similar to making a request and returning response */
Defaulthttpclient client = new Defaulthttpclient ();
list<namevaluepair> list = new arraylist<namevaluepair> ();
Namevaluepair Pair1 = new Basicnamevaluepair ("name", Name.gettext (). toString ());
Namevaluepair Pair2 = new Basicnamevaluepair ("Age", Age.gettext (). toString ());
List.add (PAIR1);
List.add (PAIR2);
urlencodedformentity entity = new Urlencodedformentity (list, "UTF-8");
HttpPost post = new HttpPost ("Http://192.168.0.103:8080/Server/Servlet1");
Post.setentity (entity);
HttpResponse response = Client.execute (POST);
if (Response.getstatusline (). Getstatuscode () ==200) {
InputStream in = Response.getentity (). getcontent ();//Receive server data and display on toast
String str = readString (in);
Toast.maketext (Mainactivity.this, str, toast.length_short). Show ();
}
else Toast.maketext (Mainactivity.this, "Post submission failed", Toast.length_short). Show ();
}
if (getbutton==v) {
Defaulthttpclient client = new Defaulthttpclient ();
StringBuilder buf = new StringBuilder ("Http://192.168.0.103:8080/Server/Servlet1");
Buf.append ("?");
Buf.append ("Name=" +urlencoder.encode (Name.gettext (). toString (), "UTF-8") + "&");
Buf.append ("age=" +urlencoder.encode (Age.gettext (). toString (), "UTF-8"));
HttpGet get = new HttpGet (buf.tostring ());
HttpResponse response = Client.execute (get);
if (Response.getstatusline (). Getstatuscode () ==200) {
InputStream in = Response.getentity (). getcontent ();
String str = readString (in);
Toast.maketext (Mainactivity.this, str, toast.length_short). Show ();
}
else Toast.maketext (mainactivity.this, "Get Commit Failed", Toast.length_short). Show ();
}
}
catch (Exception e) {}
}
};
@Override
public void OnCreate (Bundle savedinstancestate) { super.oncreate ( savedinstancestate); setcontentview (r.layout.main); name = (EditText) This.findviewbyid (r.id.name); age = (EditText) This.findviewbyid (r.id.age); Getbutton = (Button) This.findviewbyid (R.id.getbutton); Postbutton = (Button) This.findviewbyid (R.id.postbutton); Getbutton.setonclicklistener (listener); Postbutton.setonclicklistener (listener); } protected String ReadString (InputStream in) throws Exception { byte[]data = new byte[ 1024]; &NBsp; int length = 0; Bytearrayoutputstream bout = new Bytearrayoutputstream (); while (( Length=in.read (data)!=-1) { bout.write ( data,0,length); } return new String (Bout.tobytearray (), "UTF-8"); } }
HTTP request-android