We all know that you can use a class that inherits the Asynctask to implement asynchronous operations, and then an HTTP request class can be solved, now I say the details of the problem, such as a long time no response, coding problems, as well as some HTML-related processing.
First of all, the long-time unresponsive problem, Asynctask has a Get method,
/*** Waits if necessary for in most of the given time for the computation * to complete, and then retrieves its res Ult. * * @paramtimeout time to wait before cancelling the operation. * @paramUnit the time unit for the timeout. * * @returnThe computed result. * * @throwscancellationexception If the computation was cancelled. * @throwsexecutionexception If The computation threw an exception. * @throwsinterruptedexception If The current thread is interrupted * while waiting. * @throwstimeoutexception If The wait timed out. */ Public FinalResult Get (LongTimeout, timeunit unit)throwsinterruptedexception, Executionexception, timeoutexception {returnMfuture.get (timeout, unit); }
You can see that calling this method will have an exception, can be handled in exceptional cases, in fact, this minute is very thin, there are network exceptions, execution exceptions, time-out exceptions, you can refer to the following code to implement, will call Asynctask cancel operation of the Cancel (Boolean flag) method.
New Articletask (); Task.execute (Artitlc_url); // more than 5s clock does not complete, cancels this asynchronous operation Try { task.get (timeunit.milliseconds); Catch (Interruptedexception | executionexception | timeoutexception e) { // TODO auto-generated catch block e.printstacktrace (); Task.cancel (false); Dialog.dismiss (); }
Then say if it is the request of the HTML response, how to handle the HTML tag, here is the simple processing, detailed also use other methods, later add it. The following code basically illustrates the problem.
// Remove HTML Tags spanned spanned = html.fromhtml (result); New TextView (mainactivity. this); Textview.settext (spanned); ); // is a label generated link in the return Textview.setmovementmethod (new Linkmovementmethod ());
Finally, the transmission process of the coding problem, in fact, mainly for the Chinese language. If there are parameters, parameters to transcode, return the content also to transcode, so to involve two places, the following code comment should be able to say clearly. Initially did not notice, the result garbled, later use Result=new String (result.getbytes ("iso-8859-1"), "Utf-8"); Also solved, but look at the following method is more convenient.
//Encapsulating a form if(NULL! = Params &&!Params.isempty ()) {List<BasicNameValuePair> parameters =NewArraylist<basicnamevaluepair>(); for(Map.entry<string, object>Entry:params.entrySet ()) {String name=Entry.getkey (); String value=Entry.getvalue (). toString (); Basicnamevaluepair pair=NewBasicnamevaluepair (name, value); Parameters.Add (pair); } Try { //in order to avoid Chinese garbled, to be safe to add encoding formatUrlencodedformentity encodedformentity =Newurlencodedformentity (parameters, encoding); Post.setentity (encodedformentity); } Catch(unsupportedencodingexception e) {//TODO auto-generated Catch blockE.printstacktrace (); LOG.D ("Shang", "Unsupportedencodingexception"); } } Try{HttpResponse response=Client.execute (POST); if(HTTP_STATUS_OK = =response.getstatusline (). Getstatuscode ()) { //gets the return result of the server request, note that the encoding format is added for insurance purposes hereresult =entityutils.tostring (Response.getentity (), encoding); } Else { Throw NewException ("Invalide response from API" +response.tostring ()); } } Catch(clientprotocolexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }
There is another person's solution, but did not solve my problems at the time, also listed, some places can be borrowed.
PublicMap<string, Object> Createnote (intalbumID, string title, string remark) {String Noteid= ""; Map<string, object> map =NewHashmap<string, object>(); Try{httpparams parms=NewBasichttpparams (); Parms.setparameter ("CharSet", HTTP. UTF_8); Httpconnectionparams.setconnectiontimeout (Parms,8 * 1000); Httpconnectionparams.setsotimeout (Parms,8 * 1000); HttpClient HttpClient=Newdefaulthttpclient (parms); HttpPost HttpPost=NewHttpPost (Confighelper.createuri); Httppost.addheader ("Authorization", Mtoken); Httppost.addheader ("Content-type", "Application/json"); Httppost.addheader ("CharSet", HTTP. UTF_8); Jsonobject obj=NewJsonobject (); Obj.put ("Title", title); Obj.put ("CategoryId", Mcategoryid); Obj.put ("sourceURL", Getsourceuri ()); Jsonarray arr=NewJsonarray (); Arr.put (Dateformat.format ("Yyyymm", Calendar.getinstance (Locale.china))); Obj.put ("Tags", arr); Obj.put ("Content", remark); Httppost.setentity (Newstringentity (obj.tostring (), HTTP. Utf_8)); HttpResponse response; Response=Httpclient.execute (HttpPost); intCode =response.getstatusline (). Getstatuscode (); if(Code = =ConstanDefine.ErrorCode.SuccOfHttpStatusCode) {String Rev=entityutils.tostring (Response.getentity ()); Obj=NewJsonobject (rev.); Noteid= obj.getstring ("id"); Map.put ("Return_code", "0"); Map.put ("Content", rev.); } } Catch(Exception e) {if(Map.containskey ("Return_code") {map.remove ("Return_code"); } map.put ("Return_code", "1"); } returnmap;}
Android about asynchronous HTTP requests, and encoding issues