Android Network connection httpurlconnection and HttpClient

Source: Internet
Author: User

1. Concept

The HTTP protocol is probably the most widely used and most important protocol on the Internet now, and more and more Java applications need to access network resources directly through the HTTP protocol. The basic functionality for accessing the HTTP protocol has been provided in the JDK's java.net package: HttpURLConnection. For most applications, however, the JDK library itself offers less functionality and flexibility.

In addition, in Android, theApache httpclient module is integrated in ANDROIDSDK to provide an efficient, up-to-date, feature-rich support HTTP protocol toolkit, and it supports HTTP The latest version and recommendations of the Agreement. Using httpclient, you can quickly develop powerful HTTP programs.

2. Differences

HttpClient is a great open source framework that encapsulates the request headers, parameters, contents, responses, and so on for HTTP access.

HttpURLConnection is the standard class for Java, with nothing encapsulated, too primitive and inconvenient to use, such as the customization of re-access , and some advanced features.

URLConnection

HTTPClient

Proxies and SOCKS

Netscape Browser, Appletviewer, and Applications (socks:version 4 only); No additional limitations from security policies.

Full Support (Socks:version 4 and 5); Limited in applets however by security policies; In Netscape can ' t pick to the settings from the browser.

Authorization

Full-Support-Basic Authorization in Netscape (can use info given by the user for normal accesses outside of the applet ); No support in Appletviewer or applications.

Full support everywhere; However cannot access previously given info from Netscape, thereby possibly requesting the user to enter info (s) he had AL Ready given for a previous access. Also, you can add/implement additional authentication mechanisms yourself.

Methods

Only have GET and POST.

Have HEAD, GET, POST, PUT, DELETE, TRACE and OPTIONS, plus any arbitrary method.

Headers

Currently you can only set any request headers if is doing a POST under Netscape; For GETs and the JDK can ' t set any headers.
Under Netscape 3.0 You can read headers only if the resource is returned with a content-length header; If no content-length header is returned, or under previous versions of Netscape, or using the JDK no headers can be read.

Allows any arbitrary headers to be sent and received.

Automatic Redirection Handling

Yes.

Yes (as allowed by the http/1.1 spec).

Persistent Connections

No support for currently in JDK; Under Netscape uses http/1.0 keep-alive ' s.

Supports http/1.0 keep-alive ' s and http/1.1 persistence.

Pipelining of Requests

No.

Yes.

Can handle protocols other than HTTP

theoretically; However only HTTP is currently implemented.

No.

Can do HTTP over SSL (HTTPS)

Under Netscape, yes. Using Appletviewer or in an application, No.

No (not yet).

Source Code available

No.

Yes.

3. Case studies

URLConnection

    String urladdress = "Http://192.168.1.102:8080/AndroidServer/login.do";  
URL url;
HttpURLConnection URLConnection;
Public Urlconnectiontoserver () {

}
Send a GET request to the server
public string doget (string username,string password) {
String GETURL = urladdress + "? username=" +username+ "&password=" +password;
try {
url = new URL (getUrl);
URLConnection = (httpurlconnection) url.openconnection ();
InputStream is = Urlconnection.getinputstream ();
BufferedReader br = new BufferedReader (new InputStreamReader (IS));
String response = "";
String readLine = null;
while ((ReadLine =br.readline ()) = null) {
Response = Br.readline ();
Response = response + ReadLine;
}
Is.close ();
Br.close ();
Urlconnection.disconnect ();
return response;
} catch (Malformedurlexception e) {
E.printstacktrace ();
return null;
} catch (IOException e) {
E.printstacktrace ();
return null;
}
}
Send a POST request to the server
public string DoPost (string username,string password) {
try {
url = new URL (urladdress);
URLConnection = (httpurlconnection) url.openconnection ();
Urlconnection.setdoinput (TRUE);
Urlconnection.setdooutput (TRUE);
Urlconnection.setrequestmethod ("POST");
Urlconnection.setusecaches (FALSE);
Urlconnection.setinstancefollowredirects (FALSE);
Urlconnection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");
Urlconnection.connect ();

DataOutputStream out = new DataOutputStream (Urlconnection.getoutputstream ());
String content = "Username=" +username+ "&password=" +password;
Out.writebytes (content);
Out.flush ();
Out.close ();

InputStream is = Urlconnection.getinputstream ();
BufferedReader br = new BufferedReader (new InputStreamReader (IS));
String response = "";
String readLine = null;
while ((ReadLine =br.readline ()) = null) {
Response = Br.readline ();
Response = response + ReadLine;
}
Is.close ();
Br.close ();
Urlconnection.disconnect ();
return response;
} catch (Malformedurlexception e) {
E.printstacktrace ();
return null;
} catch (IOException e) {
E.printstacktrace ();
return null;
}
}

HTTPClient

String urladdress = "Http://192.168.1.102:8080/qualityserver/login.do";
Public Httpclientserver () {

}

public string doget (string username,string password) {
String GETURL = urladdress + "? username=" +username+ "&password=" +password;
HttpGet httpget = new HttpGet (GETURL);
Httpparams hp = Httpget.getparams ();
Hp.getparameter ("true");
Hp.
Httpget.setp
HttpClient HC = new Defaulthttpclient ();
try {
HttpResponse ht = Hc.execute (httpget);
if (Ht.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {
Httpentity he = ht.getentity ();
InputStream is = He.getcontent ();
BufferedReader br = new BufferedReader (new InputStreamReader (IS));
String response = "";
String readLine = null;
while ((ReadLine =br.readline ()) = null) {
Response = Br.readline ();
Response = response + ReadLine;
}
Is.close ();
Br.close ();

String str = entityutils.tostring (HE);
System.out.println ("=========" +response);
return response;
}else{
return "error";
}
} catch (Clientprotocolexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
Return "Exception";
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
Return "Exception";
}
}

public string DoPost (string username,string password) {
String GETURL = urladdress + "? username=" +username+ "&password=" +password;
HttpPost HttpPost = new HttpPost (urladdress);
List params = new ArrayList ();
Namevaluepair Pair1 = new Basicnamevaluepair ("username", username);
Namevaluepair Pair2 = new Basicnamevaluepair ("password", password);
Params.add (PAIR1);
Params.add (PAIR2);

Httpentity he;
try {
he = new Urlencodedformentity (params, "GBK");
Httppost.setentity (He);

} catch (Unsupportedencodingexception E1) {
TODO auto-generated Catch block
E1.printstacktrace ();
}

HttpClient HC = new Defaulthttpclient ();
try {
HttpResponse ht = Hc.execute (HttpPost);
Connection Successful
if (Ht.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {
Httpentity het = ht.getentity ();
InputStream is = Het.getcontent ();
BufferedReader br = new BufferedReader (new InputStreamReader (IS));
String response = "";
String readLine = null;
while ((ReadLine =br.readline ()) = null) {
Response = Br.readline ();
Response = response + ReadLine;
}
Is.close ();
Br.close ();

String str = entityutils.tostring (HE);
System.out.println ("=========&&" +response);
return response;
}else{
return "error";
}
} catch (Clientprotocolexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
Return "Exception";
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
Return "Exception";
}
}

Servlet-side JSON conversion:

        Resp.setcontenttype ("Text/json");  
Resp.setcharacterencoding ("UTF-8");
Todo = new Todo ();
list<userbean> list = new arraylist<userbean> ();
List = Todo.queryusers (mysession);
String body;

Set JSON
Jsonarray array = new Jsonarray ();
for (UserBean bean:list)
{
Jsonobject obj = new Jsonobject ();
Try
{
Obj.put ("username", bean.getusername ());
Obj.put ("Password", Bean.getpassword ());
}catch (Exception e) {}
Array.add (obj);
}
Pw.write (Array.tostring ());
System.out.println (Array.tostring ());

Android-side receive:

String urladdress = "Http://192.168.1.102:8080/qualityserver/result.do";
String BODY =
GetContent (urladdress);
Jsonarray array = new Jsonarray (body);
for (int i=0;i<array.length (); i++)
{
obj = Array.getjsonobject (i);
Sb.append ("User name:"). Append (obj.getstring ("username")). Append ("\ t");
Sb.append ("Password:"). Append (obj.getstring ("password")). Append ("\ n");

hashmap<string, object> map = new hashmap<string, object> ();
try {
UserName = obj.getstring ("UserName");
PassWord = obj.getstring ("PassWord");
} catch (Jsonexception e) {
E.printstacktrace ();
}
Map.put ("username", username);
Map.put ("password", password);
Listitem.add (map);

}

} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

if (sb!=null)
{
Showresult.settext ("User name and password information:");
Showresult.settextsize (20);
} else
Extracted ();

Set Adapter
Simpleadapter simple = new Simpleadapter (This,listitem,
Android. R.layout.simple_list_item_2,
New string[]{"username", "password"},
New Int[]{android. R.id.text1,android. R.ID.TEXT2});
Listresult.setadapter (simple);

Listresult.setonitemclicklistener (New Onitemclicklistener () {
@Override
public void Onitemclick (adapterview<?> parent, view view,
int position, long ID) {
int positionid = (int) (id+1);
Toast.maketext (Mainactivity.this, "ID:" +positionid, Toast.length_long). Show ();

}
});
}
private void extracted () {
Showresult.settext ("No valid data! ");
}
and server connections
private string getcontent (string url) throws exception{
StringBuilder sb = new StringBuilder ();
HttpClient client =new defaulthttpclient ();
Httpparams httpparams =client.getparams ();

Httpconnectionparams.setconnectiontimeout (Httpparams, 3000);
Httpconnectionparams.setsotimeout (Httpparams, 5000);
HttpResponse response = Client.execute (new HttpGet (URL));
Httpentity entity =response.getentity ();

if (entity!=null) {
BufferedReader reader = new BufferedReader (New InputStreamReader
(Entity.getcontent (), "UTF-8"), 8192);
String line =null;
while ((Line= reader.readline ())!=null) {
Sb.append (line + "\ n");
}
Reader.close ();
}
return sb.tostring ();
}

Android Network connection httpurlconnection and HttpClient

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.