Network request communication topic for Android Development (I): HttpURLConnection-based request Communication

Source: Internet
Author: User

Network request communication topic for Android Development (I): HttpURLConnection-based request Communication

In Android development, network requests must be indispensable. Generally, all are http-based network requests. Sometimes there will also be SOCKET requests, which will be discussed later in this topic. Today, let's talk about common Http requests.

Http requests follow the http protocol. For details, refer to the Http protocol for Java study notes.

Now, let's start with today's question.


I. Basic HTTPURL Request Method let's take a look at the simplest example. get the return value through the get Method Request. 1. get the request.
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 = 200) {input = conn. getInputStream (); if (input! = Null) {// post-processing after obtaining the stream }}

2. post request
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 the input of conn. setDoOutput (true); // allow the output of conn. setUseCaches (false); // do not use Cacheconn. setRequestProperty ("Charset", ENCODING); conn. setRequestPro Perty ("Content-Length", String. valueOf (data. length (); conn. setRequestProperty ("Content-Type", "text/*; charset = UTF-8"); conn. setRequestMethod ("POST"); DataOutputStream outStream = new DataOutputStream (conn. getOutputStream (); outStream. write (data. getBytes (); outStream. flush (); outStream. close (); if (conn = null) {return;} int responseCode = conn. getResponseCode (); if (responseCode = 200) {input = conn. g EtInputStream (); if (input! = Null ){}}

We can see that the post request is a little different from the get request.
Ii. encapsulation of http Response classes
1. encapsulation logic we know that in android development, network access tasks cannot be executed in the UI thread and can only be executed in the Child thread, notify the main thread to refresh the UI after the result is obtained. This message notification mechanism is not described in detail by the blogger. If you are interested, please transfer: Android asynchronous processing series of article indexes are under normal development and we will not request each time, the Code is as simple as above. We need to encapsulate it to make the code more concise and the architecture clearer. So we need four things.
1. http Access Manager 2. Message Communication Manager handler3. http access result listener 4. http access result event processing callback interface. The entire logic is as follows: the http access manager sends a get or post request. After the result is generated, the listener tells the Message Communication Manager What messages should be sent to the UI thread, the UI thread calls the corresponding event processing callback interface for messages sent by message communication managers.
Let's look at how to write these four classes one by one.
2. http access manager the http access manager needs to encapsulate two types of requests as its name. Under normal circumstances, when constructing an http access manager, you need to pass in a communication protocol class, which should contain the request address and request information. Here, the blogger facilitates the convenience of convenience, no entry or exit. If you are interested, you can change it based on your actual needs. Check 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 ← _freedom (x_freedom_reddevil@126.com) * @ createddate 1:43:58 * @ Description: http request manager */public class 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;/** get stream */InputStream input = null; private static final String ENCODING = "UTF-8"; public static final int GET_MOTHOD = 1; private static final int TIME = 40*1000; public static final int POST_MOTHOD = 2; /*** 1: get request 2: post Request */private int requestStatus = 1 ;/***

* Title :*

*

* Description: constructor. In fact, a transfer protocol package can be imported here. The blogger is testing code, so the request is directly written to the dead. *

** @ Param mContext * @ param listener * @ param mRequeststatus * Request Method */public FreedomHttpUrlUtils (Context mContext, FreedomHttpListener listener, int mRequeststatus) {this. context = mContext; this. requestStatus = mRequeststatus; this. listener = listener;}/*** @ Title: postRequest * @ Description: Post request trigger * @ throws */public void postRequest () {requestStatus = 2; currentRequest = new Thread (this); cu R0000request. start ();}/*** @ Title: getRequeest * @ Description: GET request trigger * @ throws */public void getRequeest () {requestStatus = 1; currentRequest = new Thread (this); currentRequest. start ();}/*** encode the request String ** @ return * @ throws UnsupportedEncodingException */public static String requestEncodeStr (String requestStr) throws UnsupportedEncodingException {return URLEncoder. encode (requestStr, ENCODING );}/* ** @ Title: sendGetRequest * @ Description: Send a get request * @ throws */private void sendGetRequest () {try {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 = 200) {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 (IO Exception 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 a post Request * @ throws */private void sendPostRequest () {try {String data = "username = justice & password = infiniteJustice"; URL url = new URL ("http: // 192.16) 8.31.144: 10010/MINATest/servlet/DataTestServlet "); conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (TIME); conn. setReadTimeout (TIME); conn. setDoInput (true); // allow the input of conn. setDoOutput (true); // allow the output of conn. setUseCaches (false); // do not use Cacheconn. setRequestProperty ("Charset", ENCODING); conn. setRequestProperty ("Content-Length", String. valueOf (data. length (); conn. setRequestProperty ("Content-Ty Pe "," text/*; charset = UTF-8 "); conn. setRequestMethod ("POST"); DataOutputStream outStream = new DataOutputStream (conn. getOutputStream (); outStream. write (data. getBytes (); outStream. flush (); outStream. close (); if (conn = null) {return;} int responseCode = conn. getResponseCode (); if (responseCode = 200) {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. EVENT_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 (); list Ener. 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: determines whether access to * @ 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 inStream) throws Exception {String result; byteArrayOutputStream outStream = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int len =-1; while (len = inStream. read (buffer ))! =-1) {outStream. write (buffer, 0, len);} result = new String (outStream. toByteArray (), ENCODING); outStream. close (); inStream. close (); return result;}/*** cancel 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 () {// determine whether a network is available boolean netType = NetUtils. checkNetWork (context); if (netType) {if (requestStatus = 1) {sendGetRequest ();} else if (requestStatus = 2) {sendPostRequest ();}} else {listener. action (FreedomHttpListener. EVENT_NOT_NETWORD, null );}}}

We can see that when there is a result for access, the listener's action method will be triggered, so let's take a look at the listener Definition 3. http access result listener
Package com. example. nettest;/*** @ ClassName: FreedomHttpListener * @ author victor_freedom (x_freedom_reddevil@126.com) * @ createddate 4:28:31 * @ Description: listener */public interface FreedomHttpListener {public static final int EVENT_BASE = 0x100;/*** no network information prompt **/public static final int EVENT_NOT_NETWORD = EVENT_BASE + 1; /*** network exception message **/public static final int EVENT_NETWORD_EEEOR = EVENT_BASE + 2; /*** failed to get Network Data **/public static final int EVENT_GET_DATA_EEEOR = EVENT_BASE + 3; /*** network data obtained successfully **/public static final int EVENT_GET_DATA_SUCCESS = EVENT_BASE + 4; /*** network data obtained successfully **/public static final int EVENT_CLOSE_SOCKET = EVENT_BASE + 5; public void action (int actionCode, Object object );}

We can see that when an action is triggered, a code and an object are passed in. This code indicates whether the current access is successful, and the object is the access result to be transmitted. Let's look at how the message processor works.
4. message processor
/*** @ ClassName: BaseHandler * @ author Handler _freedom (x_freedom_reddevil@126.com) * @ createddate 4:32:05 * @ Description: message processor */class BaseHandler extends Handler {private Context context Context; /** Event callBack interface processing */private FreedomDataCallBack callBack; public BaseHandler (Context context, FreedomDataCallBack callBack) {this. context = context; this. callBack = callBack;} public void handleMessage (Message msg) {// trigger different actions if (msg. what = FreedomHttpListener. EVENT_GET_DATA_SUCCESS) {if (msg. obj = null) {callBack. onFailed ();} else {// backend 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 ();}}

We can see that a callback interface class is introduced in the message processor to trigger different callback actions in different returned results.
5. Callback Interface
Package com. example. nettest;/*** @ ClassName: FreedomDataCallBack * @ author __freedom (x_freedom_reddevil@126.com) * @ createddate 4:33:38 * @ Description: callback interface, processing returned data * @ param
 
  
*/Public interface FreedomDataCallBack
  
   
{Public abstract void onStart (); public abstract void processData (T paramObject, boolean paramBoolean); public abstract void onFinish (); public abstract void onFailed ();}
  
 

Because we don't know the type of returned results, we use generics to process them here.

Iii. Use of http encapsulation 1. How to use it after we have encapsulated everything from the server's data retrieval method? Let's try to write a method to get data from the server and return it. First, write a getDataFromserver method in the base class.
/*** @ Title: getDataFromServer * @ Description: get data from the server * @ param requestType * Request Method * @ param callBack * callBack interface * @ throws */protected void getDataFromServer (int requestType, FreedomDataCallBack callBack) {final BaseHandler handler = new BaseHandler (this, callBack); freedomHttpUrlUtils = new FreedomHttpUrlUtils (mContext, new FreedomHttpListener () {@ Overridepublic void action (int actionCode, Object object) {Message msg = new Message (); switch (actionCode) {case FreedomHttpListener. 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 different request methods if (requestType = FreedomHttpUrlUtils. GET_MOTHOD) {freedomHttpUrlUtils. getRequeest ();} else if (requestType = FreedomHttpUrlUtils. POST_MOTHOD) {freedomHttpUrlUtils. postRequest ();}}

2. Use this method in the main Activity. For convenience, the blogger returns the parameters for any submitted parameters. The parameters submitted here are in the username and password format. For detailed request parameters, see FreedomHttpUrlUtils. Let's first look at the processing method of the server:
@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));}

Let's look at the calls in activity:
/*** @ ClassName: MainActivity * @ author ready _freedom (x_freedom_reddevil@126.com) * @ createddate 4:40:59 * @ Description: TODO */public class MainActivity extends BaseActivity {private TextView get; private TextView post; @ Overrideprotected void findViewById () {get = (TextView) findViewById (R. id. hello); post = (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
 
  
() {@ Overridepublic void onStart () {}@ Overridepublic void processData (String paramObject, boolean paramBoolean) {get. setText (paramObject) ;}@ Overridepublic void onFinish () {}@ Overridepublic void onFailed () {}}); getDataFromServer (2, new FreedomDataCallBack
  
   
() {@ Overridepublic void onStart () {}@ Overridepublic void processData (String paramObject, boolean paramBoolean) {post. setText (paramObject) ;}@ Overridepublic void onFinish () {}@ Overridepublic void onFailed (){}});}
  
 

The two access methods are used here, and the input parameters are different. We can see the access results, and both textviews display the values returned by the access. Download function.

Related Article

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.