Use of WebView (HTTP protocol access network get and Post request method)

Source: Internet
Author: User
Tags gettext

Concept WebView use method to load page hyperlinks and local connection resource cases load HTML and local connection WebView load HTML code HTTP protocol Access network case Getpost method custom handle class to send information Get request mode to main thread Post Request method

Concept:

is an open browser component that is developed based on the WebKit kernel, like Apple Safari, Google Chrome browser is implemented through WebView,
In the Android system, the default also provides support for the WebView component, which allows users to display the content of the Web page directly using the WebView component, or embed some of the specified HTML files in the
In addition to supporting the "forward" and "back" features of each browser, the most powerful of these are JavaScript-enabled operations in the WebView component.
The inheritance structure of the Android.webkit.WebView is as follows:
Java.lang.Object
? Android.view.View
? Android.view.ViewGroup
? Android.widget.AbsoluteLayout
? Android.webkit.WebView WebView Use Method (load Web page hyperlinks and local connection resources)

WebView Control Browsing Web pages: 
    layout files using the
    loadurl (URL) method to load a Web page androidmanifest.xml webview a
    file to configure network access rights
    < Uses-permission android:name= "Android.permission.INTERNET"/>
     app:ptrmode= "Both" supports pull up and down-pull refreshes
    Set Webviewclient rewrite Shouldoverrideurlloading method
case (Mount HTML and local connection):
public class Mainactivity extends Appcompatactivity {private EditText et_url;
    Private Button Btn_open;
    Private WebView WV;

    Private ProgressBar PB;
        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
        Setcontentview (R.layout.activity_main);
    Initview ();
        private void Initview () {et_url= (edittext) Findviewbyid (R.id.et_url);
        Btn_open= (Button) Findviewbyid (R.id.btn_open);
        wv= (WebView) Findviewbyid (R.ID.WV);
        pb= (ProgressBar) Findviewbyid (R.ID.PB);
                Btn_open.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {
            Wv.loadurl (Et_url.gettext (). toString ());
        }
        });
        Set the URL you entered is open in the current browser, and no setting prompts you to open a new browser, Wv.setwebviewclient (MyClient ()); Set Load progress bar wv.setwebchromeclient (new Webchromeclient () {@Override public voID onprogresschanged (webview view, int newprogress) {super.onprogresschanged (view, newprogress);
Pb.setprogress (newprogress)//Add load Process progress bar//Settitle ("Loading ..."); if (newprogress==1) {//Pb.setvisibility (View.gone);//Settitle ("add
Load Complete ");
        //                }
            }
        });
        Loads the local HTML file, creates a new assets package under the main package, and copies the import HTML folder Wv.loadurl ("file:/android_asset/me/index.html"); Wv.getsettings (). Setbuiltinzoomcontrols (true);/support scaling wv.getsettings (). Setjavascriptenabled (true);// Allow JS script (Web dynamic Effect)} class MyClient extends webviewclient{@Override public boolean Shouldoverrideu
            Rlloading (webview view, String URL) {//Obsolete method for View.loadurl (URL) with SDK version less than 21;
        Return super.shouldoverrideurlloading (view, URL);
@Override public boolean shouldoverrideurlloading (WebView view, webresourcerequest request) {            if (build.version.sdk_int>build.version_codes.
            Lollipop///When the SDK version is greater than 21 o'clock to use this method View.loadurl (Request.geturl (). toString ());
        Return super.shouldoverrideurlloading (view, request);
 }
    }
WebView Loading HTML code (HTTP protocol access network):
    Layout files use
    loadurl ("file:/android_asset/.../xxx.html") to load HTML
  using the WebView Control assets folder with HTML code Note: Webview.getsettings (). Setjavascriptenabled (true);//enable JavaScript
      webview.getsettings (). Setbuiltinzoomcontrols (TRUE);//Control page Scaling
      androidmanifest.xml file Configure network access
      <uses-permissionandroid:name= " Android.permission.INTERNET "/>
Case Get+post Method:

Public class Mainactivity extends Appcompatactivity {
Private edittext et_user,et_password;
Private Button Btn_login;
Private Mythread Thread=null;
Private Myhandle Handle=null;
@Override
protected void onCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Initview ();
}
private void Initview () {
Handle=new myhandle ();//The instantiation of the control is also instantiated handle
et_user= (edittext) Findviewbyid ( R.id.et_user);
et_password= (EditText) Findviewbyid (R.id.et_password);
btn_login= (Button) Findviewbyid (R.id.btn_login);
Btn_login.setonclicklistener (New View.onclicklistener () {
@Override
public void OnClick (View v) {
//① real To instantiate the control, add a click event to the button, click the button to start the child thread
if (thread==null) {
Thread=new mythread ();
Thread.Start ();
}
}
});
}

/**
 *② Custom Thread
/class Mythread extends thread{//③
    rewrite the Run method
    //access network, log in, and send the results of the login to the main thread using handle. Write a method to access the network
    @Override public
    void Run () {
        super.run ();
        ⑤ calls the access network method, gets the result value
  //           String result= loginget ();
        String result=loginpost ();
    The ⑥ thread sends a message to the main thread, which requires a custom handle messages
        message= handle.obtainmessage (1,result);
      Handle.sendmessage (message);
        Message sent, thread empty, easy to use thread=null next time
        ;
    }

The custom handle class is used to send information to the main thread:

/**
*⑦ custom handle class, sending message
*
*/
Class Myhandle extends handler{
Overriding the Handlemessage method
@Override
public void Handlemessage (msg) {
Super.handlemessage (msg);
Switch (msg.what) {
Case 1:
Toast.maketext (Mainactivity.this,msg.obj.tostring (), Toast.length_short). Show ();
Break
} Get Request method:

/**
*④ defines a way to access a network
*get Request method, clear text to pass parameters
*/
Private String Loginget () {
String Username=et_user.gettext (). toString ();
String Password=et_password.gettext (). toString ();
String Strurl=null;
Input box non-null validation
if (username!=null&&password!=null) {
Strurl= "Http://192.168.15.114:8080/HttpTest/Login?username=" +username+ "&password=" +password;
}
try {
URL url=new url (strurl);
HttpURLConnection conn= (httpurlconnection) url.openconnection ();//Open connection
Conn.setrequestmethod ("get")//Set request method, uppercase get
GET request Results
int Code=conn.getresponsecode ();
if (code==200) {//request succeeded, return request result code 200, read stream result
InputStream Is=conn.getinputstream ()//Get stream file
InputStreamReader isr=new InputStreamReader (IS);//Read stream file
BufferedReader reader=new BufferedReader (ISR);//read one line at a time
String line= "";//define empty rows for append content
StringBuffer buffer=new StringBuffer ();
while ((Line=reader.readline ())!=null) {//If you haven't finished reading
Buffer.append (line)/always append content
}
Close the stream, disconnect
Reader.close ();
Conn.disconnect ();
Returns the request results obtained
return buffer.tostring ();
}else {
Return "Access failed";
}
catch (Malformedurlexception e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}
Return "Access failed";
}Post Request method:

/**
* Post Request method
* The only way to send data to a GET request is not to clear the metadata
*/
Private String Loginpost () {
String Username=et_user.gettext (). toString ();
String Password=et_password.gettext (). toString ();
String Strurl=null;
String Data=null;
Input box non-null validation
if (username!=null&&password!=null) {
Strurl= "Http://192.168.15.114:8080/HttpTest/Login";
Data= "Username=" +username+ "&password=" +password;
}
try {
URL url=new url (strurl);
HttpURLConnection conn= (httpurlconnection) url.openconnection ();//Open connection
Conn.setrequestmethod ("get")//Set request method, uppercase get
Conn.setrequestmethod ("POST");//Set the request mode to post
Allows input data to be set, allow input and output, and write date data to memory
Conn.setdoinput (TRUE);
Conn.setdooutput (TRUE);
Set the header of the request
Conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");
Conn.setrequestproperty ("Charset", "utf-8");
Conn.setrequestproperty ("Content-length", "" "+ data.getbytes (). Length);
Write Data to Memory
OutputStream Os=conn.getoutputstream ();
Os.write (Data.getbytes ());
Os.flush ()//refresh in-memory data
GET request Results
int Code=conn.getresponsecode ();
if (code==200) {//request succeeded, return request result code 200, read stream result
InputStream Is=conn.getinputstream ()//Get stream file
InputStreamReader isr=new InputStreamReader (IS);//Read stream file
BufferedReader reader=new BufferedReader (ISR);//read one line at a time
String line= "";//define empty rows for append content
StringBuffer buffer=new StringBuffer ();
while ((Line=reader.readline ())!=null) {//If you haven't finished reading
Buffer.append (line)/always append content
}
Close the stream, disconnect
Reader.close ();
Conn.disconnect ();
Returns the request results obtained
return buffer.tostring ();
}else {
Return "Access failed";
}
catch (Malformedurlexception e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}
Return "Access failed";
}

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.