"Android Combat Tour 006" HTTP communication in Android

Source: Internet
Author: User
Tags response code

For the HTTP protocol I think a lot of friends are not unfamiliar, an HTTP operation is called a transaction. The basics of HTTP include: Url,http three handshake, HTTP request header information, HTTP request mode, HTTP response Code information, HTTP protocol features, TCP/IP four layer protocol, OSI seven layer protocol, and http1.0 and http1.1 differences. There is no connection to http: Restrict each connection to only one request, the server finishes processing the customer's request, and then receives the customer's answer, which disconnects the connection. HTTP stateless: The protocol has no memory capacity for transactional processing, and a lack of state means that if the subsequent processing requires the previous information, it must be re-transmitted. Basic knowledge can be consulted: http://blog.csdn.net/davebobo/article/details/52728841

I. Introduction and use of HttpURLConnection

Case one: HTTP access Baidu, WebView display content

New HTTP_01 project, first we need to do network operation, add permission permissions in Androidmanifest.xml

<uses-permission android:name= "Android.permission.INTERNET"/>
Adding WebView components in Activity_main.xml

<webview        android:layout_width= "wrap_content"        android:layout_height= "wrap_content"        android:id= "@ +id/webview "        android:layout_alignparenttop=" true "        android:layout_alignparentleft=" true "        Android: Layout_alignparentstart= "true"        android:layout_alignparentright= "true"        android:layout_alignparentend= " True "        android:layout_alignparentbottom=" true "/>

Because the network operation is a time-consuming operation, we execute in the thread, creating the Visitweb class inherits the thread rewrite run method to handle the network time-consuming operation.

Package Com.davebobo.http_01;import Android.media.tv.tvview;import Android.os.handler;import Android.webkit.webview;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.InputStreamReader; Import Java.net.httpurlconnection;import java.net.malformedurlexception;import java.net.url;/** * Created by DaveBobo On 2016/10/9.    */public class Visitweb extends thread{private String URL;    Private WebView WebView;    Private Handler Handler;        Public visitweb (String URL, WebView WebView, Handler Handler) {this.url = URL;        This.webview = WebView;    This.handler = handler;        } @Override public void Run () {super.run ();            try {URL httpurl = new URL (URL);                try {HttpURLConnection conn = (httpurlconnection) httpurl.openconnection ();               Conn.setreadtimeout (5000);//set timeout to wait for Conn.setrequestmethod ("GET"); Final StringBuffer sb = new StringBuffer ();//cache//ThroughWeb page stream data bufferedreader reader = new BufferedReader (New InputStreamReader (Conn.getinputstream ()));                String str;                while (str = Reader.readline ())!=null) {sb.append (str);                        } handler.post (New Runnable () {@Override public void run () {                    Webview.loaddata (Sb.tostring (), "Text/html;charset=utf-8", null);            }                });            } catch (IOException e) {e.printstacktrace ();        }} catch (Malformedurlexception e) {e.printstacktrace (); }    }}
Find the WebView create Visitweb object in Mainactivity to call its start () method.

Package Com.davebobo.http_01;import Android.os.handler;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.webkit.webview;import Android.widget.imageview;public class MainActivity extends appcompatactivity {    private WebView WebView;    Private Handler Handler = new Handler ();    Private ImageView ImageView;    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        WebView = (WebView) Findviewbyid (R.id.webview);        ImageView = (ImageView) Findviewbyid (R.id.imageview);        New Visitweb ("https://www.baidu.com/", Webview,handler). Start ();        New Downimage ("Http://avatar.csdn.net/3/B/3/1_davebobo.jpg", Imageview,handler). Start ();    }}
Run the emulator to see the effect

Create the URL object, through the HttpURLConnection set the request way, get read the stream into the buffer, through the webview load the local page information.

Case two: Download pictures to local via web request

Set WebView to hidden in Activity_main.xml, add ImageView

<webview        android:visibility= "Gone"        android:layout_width= "wrap_content"        android:layout_height= " Wrap_content "        android:id=" @+id/webview "        android:layout_alignparenttop=" true "        android:layout_ Alignparentleft= "true"        android:layout_alignparentstart= "true"        android:layout_alignparentright= "true"        android:layout_alignparentend= "true"        android:layout_alignparentbottom= "true"/>    <imageview        android:layout_width= "200DP"        android:layout_height= "200DP"        android:id= "@+id/imageview"        Android:layout_centervertical= "true"        android:layout_centerhorizontal= "true"/>
Create downimage inherit from thread

Package Com.davebobo.http_01;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.environment;import Android.os.handler;import Android.widget.imageview;import Java.io.File;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import java.net.HttpURLConnection; Import Java.net.malformedurlexception;import java.net.url;/** * Created by Davebobo on 2016/10/9.    */public class Downimage extends thread{private String URL;    Private ImageView ImageView;    Private Handler Handler;        Public downimage (String URL, ImageView ImageView, Handler Handler) {this.url = URL;        This.imageview = ImageView;    This.handler = handler;        } @Override public void Run () {super.run ();            try {URL httpurl = new URL (URL);                try {HttpURLConnection conn = (httpurlconnection) httpurl.openconnection ();                Conn.setreadtimeout (5000); Conn.setrequestmethOD ("GET");                Conn.setdoinput (TRUE);                InputStream in = Conn.getinputstream ();                FileOutputStream out = null;                File downloadFile = null;                String fileName = string.valueof (System.currenttimemillis ());                    Determine if the SD card exists if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) { File parent = Environment.getexternalstoragedirectory ();//Get SD directory DownloadFile = new File (Parent,filen                    AME);                out = new FileOutputStream (downloadFile);                } byte[] B = new byte[2*1024];                int Len;                   if (Out!=null) {while (len = In.read (b))!=-1) {out.write (B,0,len);                }} final Bitmap Bitmap = Bitmapfactory.decodefile (Downloadfile.getabsolutepath ()); Handler.post (New Runnable () {@OveRride public void Run () {imageview.setimagebitmap (bitmap);            }                });            } catch (IOException e) {e.printstacktrace ();        }} catch (Malformedurlexception e) {e.printstacktrace (); }    }}
Initialize the ImageView component in Mainactivity and call the Start () method.

Package Com.davebobo.http_01;import Android.os.handler;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.webkit.webview;import Android.widget.imageview;public class MainActivity extends appcompatactivity {    private WebView WebView;    Private Handler Handler = new Handler ();    Private ImageView ImageView;    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        WebView = (WebView) Findviewbyid (R.id.webview);        ImageView = (ImageView) Findviewbyid (R.id.imageview);        New Visitweb ("https://www.baidu.com/", Webview,handler). Start ();        New Downimage ("Http://avatar.csdn.net/3/B/3/1_davebobo.jpg", Imageview,handler). Start ();    }}

Run effect


second, through the httpurlconnection transfer post,get parameters and garbled processing

1. Server-side

First we use MyEclipse to create a Java EE Web project with the project name Web


Create a new Myservlet servlet program, overriding the Doget and Dopost methods, in order to simply rewrite a method.

Package Com.davebobo.servlet;import Java.io.ioexception;import Java.io.printwriter;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class MyServlet extends HttpServlet {        public void doget (HttpServletRequest request, HttpServletResponse Response)             throws servletexception, IOException {        this.dopost (Request, response);    }         public void DoPost (HttpServletRequest request, httpservletresponse response)              throws servletexception, IOException {                 string name = Request.getparameter ("name");        string age = Request.getparameter ("Age"); &Nbsp;       printwriter out = Response.getwriter ();         Out.println ("name=" +name+ "age=" +age);                 System.out.println ("Name=" +name);        system.out.println ("age=" +age);         }}
Add a form form to index.jsp to access the servlet through action

    <form action= "Servlet/myservlet" method= "get" >    name:<input type= "text" name= "name" ><br/>    age:<input type= "text" name= "age" ><br/>    submit:<input type= "Submit" value= "Submit" >< Br/>    </form>
Run effect





If we enter Chinese in the background at this time, what happens backstage?

This is because index.jsp set the pageencoding= "Iso-8859-1", submitted to the background myservlet here need to do transcoding operations,








"Android Combat Tour 006" HTTP communication in Android

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.