Android Access HTTP server via Get,post mode

Source: Internet
Author: User
Tags http post

Rt.. I previously felt that Android network communication is amazing, magic ... Recently learned the network knowledge, now to summarize how to do

Well, let's take an example to illustrate the principle.

The use of this demo:

1. Users can access a Web page

2. The user submits the user name and password to the HTTP server, displaying the submitted content in the Tomcat console.

Let's start by introducing how to access the Web page

Look at the code

Package Com.hwb.service;import Java.net.httpurlconnection;import Java.net.url;import com.hwb.utils.StringReader; public class htmlcontentservice{    /**     * Follow the path to get data      * @param path access  Path      * @return Results      * @throws exception     */    public Static byte[] GetContent (String path) throws exception    {        url URL = new URL (path);//Build a URL object         httpurlconnection httpurlconnection = ( httpurlconnection) url.openconnection ();//Get Linked objects          Httpurlconnection.setrequestmethod ("POST");//Set Request method          Httpurlconnection.setreadtimeout (5000);///Set time-out         if ( Httpurlconnection.getresponsecode () ==200)//Get response codes         {                       byte[] arr = new byte[1024];             int res = -1;            while (res = In.read (arr))! =-1)    &nbsp ;        {                 Bytearrayoutputstream.write (arr, 0,res);            }            bytearrayoutputstream.close ();             in.close ();            return Bytearrayoutputstream.tobytearray ();                     }        return null;    }}

In this simple way we can make an HTTP request, the request results can be read into binary data, and then in the corresponding operation, for example, we can get a website source code, and so on.

In the application, we may return an XML file or a JSON-formatted string from the HTTP server, and we can get the binary data in this way and then handle the data accordingly.

Okay, now introduce the data to the HTTP server via Get,post

First we need an HTTP server, I take Tomcat to illustrate, first build a simple Web application.

Look at this servliet.

Package Com.hwb.control;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;/** * * * @ProjectName: [ Webprovider] * @Package: [Com.hwb.control] * @ClassName: [userservlet] * @Author: [HWB] * @CreateDa TE: [2014-6-7 pm 4:15:57] * @UpdateUser: [HWB] * @UpdateDate: [2014-6-7 PM 4:15:57] * @UpdateRemark: [Explain the changes in this * @Version: [v1.0] */public class Userservlet extends httpservlet{/** * Accepts 2 parameters, prints it out on the console */public void doget (Http ServletRequest request, HttpServletResponse response) throws Servletexception, ioexception{string name = Request.getparameter ("name"); String Password = request.getparameter ("password"); System.out.println ("name =" + name + ", password =" + password);} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException{doget (request,response);}} 


OK, let's build an Android app

I built a 4.4.

Now just look at the key code

Package Com.hwb.service;import Java.io.ioexception;import Java.io.outputstream;import java.net.HttpURLConnection;  Import Java.net.malformedurlexception;import Java.net.url;import Java.net.urlencoder;public class UserService{/** * A simple choke method to submit data to the HTTP server by get method * @param path Access URL * @param userName uploaded username * @param passWord password * @return upload success */public s Tatic Boolean Senddatabyget (string path, String username,string passWord) {Try{stringbuilder StringBuilder = new StringBuilder (path);//Encode Stringbuilder.append ("? Name="). Append (Urlencoder.encode (userName, "UTF-8"). Append (" &password= "). Append (Urlencoder.encode (password," UTF-8 ")); URL url = new URL (stringbuilder.tostring ()); HttpURLConnection httpurlconnection = (httpurlconnection) url.openconnection (); Httpurlconnection.setrequestmethod ( "GET"); Httpurlconnection.setconnecttimeout (Httpurlconnection.getresponsecode () ==200) {return true;}} catch (Malformedurlexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (IOEXception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return false;} /** * * @param path PATH * @param userName user name * @param passWord password * @return result */public static Boolean senddatabypost (St    Ring path, String username,string passWord) {try{url url = new URL (path);        HttpURLConnection httpurlconnection = (httpurlconnection) url.openconnection ();    StringBuilder builder = new StringBuilder (); Builder.append ("Name="). Append (Urlencoder.encode (userName, "UTF-8")). Append ("&password="). Append (    Urlencoder.encode (PassWord, "UTF-8"));    byte[] arr = builder.tostring (). GetBytes ();    Httpurlconnection.setrequestmethod ("POST");    Httpurlconnection.setconnecttimeout (5000); Httpurlconnection.setdooutput (TRUE);//set can write Data Httpurlconnection.setrequestproperty ("Content-type", "application/ X-www-form-urlencoded ")///Set HTTP POST request header Information Request data content Type Httpurlconnection.setrequestproperty (" Content-length ", String.valueof (Arr.length));//Set the length of the header information request data for the HTTP POST request OutputStream Outputstream = Httpurlconnection.getoutputstream (); Outputstream.write (arr);//writes data to the stream if (Httpurlconnection.getresponsecode (    ) {==200) {return true; }} catch (Malformedurlexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//To Do auto-generated catch Blocke.printstacktrace ();} return false;}}


I learned a few points of knowledge, now summarize

1. The first is the difference between get and post requests. Everyone knows that get is followed by a URL path followed by a parameter, and post is placed in the request body. I used a simple tool to intercept the request and you can look at this comparison

So what about Chinese?

Take a look at get

Please look at the post


Well, from these pictures we know some knowledge points and solutions. First, the browser will encode the data for us. Second, the post is not putting the data in the head

OK now to solve the coding problem, since we know that the browser will help us code, then we need to decode the data in order to get it.

Let's first popularize some of the knowledge and then say

I read this article, make a simple summary.

For Get mode, the browser is eventually submitted to the server in a iso8859-1 manner, assuming my server is Tomcat, it is the default encoding is also iso8859-1, if we directly through the Request.getparameter (); To obtain data, often garbled, the reason is that when we submit the time may first use UTF-8 or GBK way of advanced line coding. The workaround is to write a coded filter that is specifically filtered for GET requests. My demo, my client is coded in UTF-8, so I can do it.

New String (Value.getbytes ("iso-8859-1"), "UTF-8");
Specific code see below

Now we're talking about post, and we can just specify the encoding to get the right data.

All right, look at all the code.

Package Com.hwb.filter;import Java.io.ioexception;import Javax.servlet.filter;import javax.servlet.FilterChain; Import Javax.servlet.filterconfig;import Javax.servlet.servletexception;import javax.servlet.ServletRequest; Import Javax.servlet.servletresponse;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class Encodingfilter implements Filter{public void DoFilter ( ServletRequest arg0, Servletresponse arg1,filterchain arg2) throws IOException, servletexception{//TODO Auto-generated Method Stubhttpservletrequest HttpServletRequest = (httpservletrequest) arg0; HttpServletResponse HttpServletResponse = (httpservletresponse) arg1; String method = Httpservletrequest.getmethod (), if (Method.equals ("GET")) {encodingwrap encodingwrap = new Encodingwrap ( HttpServletRequest); Arg2.dofilter (Encodingwrap, httpservletresponse);} else if (method.equals ("POST")) {httpservletrequest.setcharacterencoding ("UTF-8");//You must set the encoding method Arg2.dofilter ( HttpServletRequest, HttpServletResponse);}}} Package Com.hwb.filter;import Java.io.unsupportedencodingexception;import javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.httpservletrequestwrapper;public class Encodingwrap extends httpservletrequestwrapper{ Public Encodingwrap (HttpServletRequest request) {super (request);} @Overridepublic string GetParameter (string name) {//TODO auto-generated method stubif (name==null) return Null;else { String value = Super.getparameter (name); Try{return New String (Value.getbytes ("iso-8859-1"), "UTF-8");} catch ( Unsupportedencodingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} return null;}}



Well, that's roughly the case, please point it out incorrectly!


--------------------------------------------------------------

If you are uploading a file, it is best to do it with a socket because the HTTP server has a limit on the size of the request data file

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.