Android Development Network Request Communication Topic (i): HttpURLConnection-based request communication

Source: Internet
Author: User

In Android development, network requests must be essential. Generally speaking, HTTP-based network requests are required. Sometimes there will be a socket request, this follow-up topic again. Today, we'll talk about common HTTP requests first.

HTTP plea nature is to follow the HTTP protocol, related content please transfer: Java Learning Notes HTTP protocol

Okay, get to the point today.


First, the basic Httpurl request WayLet's look at the simplest example of a GET method request to get a return value of 1, request with get
URL url = new URL ("http://192.168.31.144:10010/MINATest/servlet/DataTestServlet?username=victor&password= Strikefreedom "); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (time); Conn.setreadtimeout (time); int responsecode = Conn.getresponsecode (); if (Responsecode = = $) {input = Conn.getinputstream (); if (input! = NULL) {//Get stream post processing}}

2. Request by post
String data = "Username=justice&password=infinitejustice"; URL url = new URL ("Http://192.168.31.144:10010/MINATest/servlet/DataTestServlet"); conn = (httpurlconnection) Url.openconnection (); Conn.setconnecttimeout (time); Conn.setreadtimeout (time); Conn.setdoinput (true);// Allow input conn.setdooutput (true),//Allow output conn.setusecaches (false),//Do not use Cacheconn.setrequestproperty ("Charset", ENCODING ); Conn.setrequestproperty ("Content-length", String.valueof (Data.length ())); Conn.setrequestproperty (" Content-type "," Text/*;charset=utf-8 "), Conn.setrequestmethod (" POST ");D ataoutputstream OutStream = new DataOutputStream (Conn.getoutputstream ()); Outstream.write (Data.getbytes ()); Outstream.flush (); OutStream.close (); if (conn = = null) {return;} int responsecode = Conn.getresponsecode (), if (Responsecode = =) {input = Conn.getinputstream (); if (input! = null) {}}

We can see that it is a little different to request by post and to pass in parameters with get.
Ii. encapsulation of HTTP access classes
1. Package LogicWe know that in Android development, the network access to things can no longer be executed in the UI thread, can only be executed within the child thread, the result is notified to the main thread to refresh the UI. This notification mechanism blogger is not in detail second speed, interested friends please transfer: Android asynchronous Processing series Article indexIn normal development, we do not each request, as the above simple to write, we need to do a certain package processing, to make the code more concise, more clear architecture. Then we need four of these things.
1, HTTP Access Manager 2, message Communication Manager Handler3, HTTP access result Listener 4, HTTP access result event processing callback interface.The entire logical relationship is: The HTTP access manager takes a GET or POST request request, when the result of the listener tells the message Communication Manager what message should be sent to the UI thread, the UI thread more with the message communication Manager sent over the message, call the corresponding event processing callback interface.
So let's go to one by one to see how these four classes are written.
2. HTTP Access ManagerHTTP access managers, such as their name, need to encapsulate two kinds of requests. Under normal circumstances, in the construction of the HTTP access Manager, you need to pass in a communication protocol class entered, which should contain the request address and request information, where bloggers in order to facilitate the convenience, no access, directly written dead. Interested students can change according to their actual needs. Look at the code:
Package Com.example.nettest;import Java.io.bytearrayoutputstream;import Java.io.dataoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.unsupportedencodingexception;import Java.net.httpurlconnection;import Java.net.socketexception;import Java.net.sockettimeoutexception;import Java.net.url;import Java.net.urlencoder;import Java.util.hashmap;import Java.util.map;import Android.content.context;import android.text.textutils;import android.util.log;/** * @ClassName: FreedomHttpUrlUtils * @author victor_freedom ([email protected]) * @createddate 2015-1-22 PM 1:43:58 * @Description: HTTP request manager */public CL Freedomhttpurlutils implements Runnable {private Context context;/** HTTP access result listener */private Freedomhttplistener  listener;/** current Access thread */private thread currentrequest = null;/** Access link */httpurlconnection conn = null;/** received stream */inputstream input = null;private static final String ENCODING = "UTF-8";p ublic static final int get_mothod = 1;private static final I NtTime = 1000;public static final int post_mothod = 2;/** * 1:get request 2:post request */private int requeststatus = 1;/** * &L t;p> * Title: * </p> * <p> * Description: Construction method, in fact, here can pass in a transport protocol package, Bo Master is the test code, so the request is directly written dead. * </p> * * @param mcontext * @param listener * Listener * @param mrequeststatus * Request Mode */public Fr Eedomhttpurlutils (Context mcontext, Freedomhttplistener listener,int mrequeststatus) {this.context = MContext; This.requeststatus = Mrequeststatus;this.listener = Listener;} /** * @Title: Postrequest * @Description:P OST request triggered * @throws */public void Postrequest () {requeststatus = 2;currentrequest = new Thread (this); Currentrequest.start ();}  /** * @Title: Getrequeest * @Description: GET request trigger * @throws */public void Getrequeest () {requeststatus = 1;currentrequest = New Thread (this); Currentrequest.start ();} /** * Encode the requested String * * @return * @throws unsupportedencodingexception */public static string Requestencodestr (String Reque STSTR) throws Unsupportedencodingexception {return Urlencoder.encode (requeststr, ENCODING);} /** * @Title: Sendgetrequest * @Description: Send GET request * @throws */private void Sendgetrequest () {try {URL url = new URL ("HT Tp://192.168.31.144:10010/minatest/servlet/datatestservlet?username=victor&password=strikefreedom "); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (time); Conn.setreadtimeout (time); int responsecode = Conn.getresponsecode (); if (Responsecode = = $) {input = Conn.getinputstream (); if (input! = null) {listener.action (freedomhttplistener.event_get_data_success, Readstream (input));}} else {listener.action (freedomhttplistener.event_netword_eeeor, NULL);}} catch (SocketException e) {e.printstacktrace (); listener.action (freedomhttplistener.event_close_socket, null);} catch (Sockettimeoutexception e) {e.printstacktrace (); Listener.action (Freedomhttplistener.event_netword_eeeor, NULL);} catch (IOException e) {e.printstacktrace (); Listener.action (FreedomhTtplistener.event_get_data_eeeor, null);} catch (Exception e) {e.printstacktrace (); listener.action (freedomhttplistener.event_netword_eeeor, NULL);}} /** * @Title: Sendpostrequest * @Description: Send POST request * @throws */private void Sendpostrequest () {try {String data = "Use Rname=justice&password=infinitejustice "; URL url = new URL ("Http://192.168.31.144:10010/MINATest/servlet/DataTestServlet"); conn = (httpurlconnection) Url.openconnection (); Conn.setconnecttimeout (time); Conn.setreadtimeout (time); Conn.setdoinput (true);// Allow input conn.setdooutput (true),//Allow output conn.setusecaches (false),//Do not use Cacheconn.setrequestproperty ("Charset", ENCODING ); Conn.setrequestproperty ("Content-length", String.valueof (Data.length ())); Conn.setrequestproperty (" Content-type "," Text/*;charset=utf-8 "), Conn.setrequestmethod (" POST ");D ataoutputstream OutStream = new DataOutputStream (Conn.getoutputstream ()); Outstream.write (Data.getbytes ()); Outstream.flush (); OutStream.close (); if (conn = = null) {return;} int responsecode = CONN.GEtresponsecode (), if (Responsecode = =) {input = Conn.getinputstream (); if (input! = null) {listener.action ( Freedomhttplistener.event_get_data_success,readstream (input));}} else if (responsecode = = 404) {input = Conn.geterrorstream (); if (input! = null) {listener.action (Freedomhttplistener.even T_get_data_success,readstream (input));} else {listener.action (freedomhttplistener.event_netword_eeeor,null);}} else {listener.action (freedomhttplistener.event_netword_eeeor, NULL);}} catch (SocketException e) {e.printstacktrace (); listener.action (freedomhttplistener.event_close_socket, null);} catch (Sockettimeoutexception e) {e.printstacktrace (); Listener.action (Freedomhttplistener.event_netword_eeeor, NULL);} catch (IOException e) {e.printstacktrace (); listener.action (freedomhttplistener.event_get_data_eeeor, null);} catch ( Exception e) {e.printstacktrace (); listener.action (freedomhttplistener.event_netword_eeeor, NULL);}} /** * @Title: IsRunning * @Description: Determine if you are accessing * @return * @throws */public Boolean isrunning () {if (currentrequest! = null && currentrequest.isalive ()) {return true;} return false;} /** * Read Data * * @param instream * Input stream * @return * @throws Exception */private Object readstream (InputStream InS Tream) throws Exception {String result; Bytearrayoutputstream OutStream = new Bytearrayoutputstream (); byte[] buffer = new Byte[1024];int len = -1;while (len = in Stream.read (buffer))! =-1) {outstream.write (buffer, 0, Len);} result = new String (Outstream.tobytearray (), ENCODING); Outstream.close (); Instream.close (); return result;} /** * Cancels the current HTTP connection processing */public void Cancelhttprequest () {if (currentrequest! = null && currentrequest.isalive ()) {if (input! = null) {try {input.close ();} catch (Exception e) {e.printstacktrace ()}} input = NULL;IF (conn! = null) {try {conn.disconnect ();} catch (Exception e) {e.printstacktrace ();}} conn = Null;currentrequest = null; System.GC ();}} /** * Send request */public void Run () {//To determine if there is a network Boolean netType = Netutils.checknetwork (conText), if (NetType) {if (requeststatus = = 1) {sendgetrequest ();} else if (requeststatus = = 2) {sendpostrequest ();}} else {L Istener.action (Freedomhttplistener.event_not_netword, NULL);}}}

We can see that when the access has results, the listener's action method will be set, then we'll look at the Listener Definition 3, HTTP access result listener
Package com.example.nettest;/** * @ClassName: Freedomhttplistener * @author victor_freedom ([email protected]) * @created Date 2015-1-24 pm 4:28:31 * @Description: Listener */public interface Freedomhttplistener {public static final int event_base = 0x100;/** * No network information hint * */public static final int event_not_netword = event_base + 1;/** * Network exception information hint * */public static fin  Al int event_netword_eeeor = event_base + 2;/** * Failed to get network data * */public static final int event_get_data_eeeor = Event_base + 3;/** * Get Network data success * */public static final int event_get_data_success = event_base + 4;/** * Get network data success * */public static fin Al int event_close_socket = event_base + 5;public void action (int actioncode, Object object);}

We can see that when the action is triggered, we pass in a code and an object that indicates whether the current access is successful, and the object is the access result to be transferred. Let's see how the Message Processor works.
4. Message Processor
/** * @ClassName: Basehandler * @author victor_freedom ([email protected]) * @createddate 2015-1-24 pm 4:32:05 * @Desc Ription: Message Processor */class Basehandler extends Handler {private Context context;/** event callback interface handles */private Freedomdatacallback cal Lback;public Basehandler (Context context, Freedomdatacallback callBack) {this.context = Context;this.callback = CallBack;} public void Handlemessage (Message msg) {//trigger different actions according to different results if (msg.what = = freedomhttplistener.event_get_data_success) { if (msg.obj = = null) {callback.onfailed ();} else {//Background processing data Callback.processdata (Msg.obj, True);}} else if (msg.what = = Freedomhttplistener.event_not_netword) {callback.onfailed ();//Commonutil.showinfodialog ( context,//getString (R.string.net_error));} else if (msg.what = = Freedomhttplistener.event_netword_eeeor) {callback.onfailed ();} else if (Msg.what = = Freedomhttplistener.event_get_data_eeeor) {callback.onfailed ();} else if (Msg.what = = Freedomhttplistener.event_ Close_socket) {}callback.onfinish ();}}

As we can see, a callback interface class is passed in the message handler, triggering different callback actions in different return results.
5. Callback Interface
Package com.example.nettest;/** * @ClassName: Freedomdatacallback * @author victor_freedom ([email protected]) * @created Date 2015-1-24 pm 4:33:38 * @Description: Callback interface, processing return data * @param <T> */public interface freedomdatacallback<t> {p Ublic abstract void OnStart ();p ublic abstract void ProcessData (T paramobject, Boolean Paramboolean);p ublic abstract void O Nfinish ();p ublic abstract void onfailed ();}

Because we don't know what kind of results are returned, generics are used here to handle

Third, the use of HTTP after encapsulation 1, the method of taking data from the serverHow do we use all the things that we've already encapsulated? Let's try to write a method, get the data from the server and return it. Let's first write a Getdatafromserver method in the base class
/** * @Title: Getdatafromserver * @Description: Take data from server * @param RequestType * Request method * @param CallBack * Callback interface * @throws */protected void getdatafromserver (int requesttype,freedomdatacallback callBack) {final Basehandler Han Dler = new Basehandler (this, callBack); freedomhttpurlutils = new Freedomhttpurlutils (mcontext,new Freedomhttplistener ( {@Overridepublic void action (int actioncode, Object object) {message msg = new Message (); switch (actioncode) {case freed OmHttpListener.EVENT_NOT_NETWORD:msg.what = Freedomhttplistener.event_not_netword;break;case FreedomHttpListener.EVENT_NETWORD_EEEOR:msg.what = Freedomhttplistener.event_netword_eeeor;break;case FreedomHttpListener.EVENT_CLOSE_SOCKET:msg.what = Freedomhttplistener.event_close_socket;break;case FreedomHttpListener.EVENT_GET_DATA_EEEOR:msg.what = Freedomhttplistener.event_get_data_eeeor;msg.obj = Null;break; Case FreedomHttpListener.EVENT_GET_DATA_SUCCESS:msg.obj = Object;msg.what = Freedomhttplistener.event_get_dAta_success;break;default:break;} Handler.sendmessage (msg);}}, RequestType); Callback.onstart ();//Select a different request method if (RequestType = = Freedomhttpurlutils.get _mothod) {freedomhttpurlutils.getrequeest ();} else if (RequestType = = Freedomhttpurlutils.post_mothod) { Freedomhttpurlutils.postrequest ();}}

2, the use of methodsWe enable this method in the main activity. For convenience, the blogger here is what parameters are returned when the parameter is submitted. The parameters presented here are unified in username and password form. Please see the freedomhttpurlutils for detailed parameters.Let's look at how the server handles it:
@Overridepublic void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {String parameter = Request.getparameter ("username"); String parameter2 = request.getparameter ("password"); System.out.println (parameter + parameter2); Response.setcontenttype ("Text/*;charset=utf-8"); Response.getwriter (). Write (parameter + "-" + Parameter2);} @Overridepublic void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//Doget (request, response); System.out.println ("post"); ServletInputStream InputStream = Request.getinputstream (); Byteoutputstream B = new Byteoutputstream (), int len = -1;byte[] buf = new Byte[1024];while (len = Inputstream.read (BUF)) ! =-1) {b.write (buf, 0, buf.length);} String s = b.tostring (); string[] split = S.split ("&"); System.out.println (Split[0] + split[1]); Response.setcontenttype ("Text/*;charset=utf-8"); Response.getwriter (). Write (Split[0].substring (split[0].lastindexof ("=") + 1) + "-" + Split[1].substring (split[1].lastindexof ("=") + 1)); 

We're looking at the call in the activity:
/*** @ClassName: mainactivity* @author victor_freedom ([email protected]) * @createddate 2015-1-24 4:40:59 * @ Description:todo */public class Mainactivity extends Baseactivity {private TextView get;private TextView post; @Overridep rotected void Findviewbyid () {get = (TextView) Findviewbyid (R.id.hello);p ost = (TextView) Findviewbyid (r.id.post);} @Overrideprotected void Loadviewlayout () {Setcontentview (r.layout.activity_main);} @Overrideprotected void Processlogic () {} @Overrideprotected void Setlistener () {} @Overrideprotected void init () { Getdatafromserver (1, New freedomdatacallback<string> () {@Overridepublic void OnStart () {} @Overridepublic void ProcessData (String paramobject, Boolean Paramboolean) {get.settext (paramobject);} @Overridepublic void OnFinish () {} @Overridepublic void onfailed () {}}); Getdatafromserver (2, New Freedomdatacallback <String> () {@Overridepublic void OnStart () {} @Overridepublic void ProcessData (String paramobject, Boolean Paramboolean) {Post.settext (PARamobject);} @Overridepublic void OnFinish () {} @Overridepublic void onfailed () {}});

We have two methods of access here, the parameters are also different, we look at the results of access, two TextView show the value of the access returned.



Well, the first article on HTTP access has been explained, hoping to help people who see this article. Next we explain how to use the HttpClient class to implement HTTP network requests, and implement file upload and download functions.

Android Development Network Request Communication Topic (i): HttpURLConnection-based request communication

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.