Android uses get and post methods to access the http server

Source: Internet
Author: User

RT... I used to think Android Network Communication is amazing. Magic... I recently learned about the network. Now I want to summarize how to do it.

Let's take an example to illustrate the principle.

Let's talk about the usefulness of this Demo:

1. Users can access a webpage

2. the user submits the user name and password to the Http server and displays the submitted content on the Tomcat console.

First, we will introduce how to access the webpage.

View code

Package com. hwb. service; import java.net. httpURLConnection; import java.net. URL; import com. hwb. utils. stringReader; public class HtmlContentService {/*** obtain data by path * @ param path * @ return result * @ throws Exception */public static byte [] getContent (String path) throws Exception {URL url = new URL (path); // construct a URL object HttpURLConnection httpURLConnection = (HttpURLConnection) url. openConnection (); // get the link Object httpURLConnection. setRequestMethod ("POST"); // sets the Request Method httpURLConnection. setReadTimeout (5000); // set the timeout value if (httpURLConnection. getResponseCode () = 200) // obtain the response code {byte [] arr = new byte [1024]; int res =-1; while (res = in. read (arr ))! =-1) {byteArrayOutputStream. write (arr, 0, res);} byteArrayOutputStream. close (); in. close (); return byteArrayOutputStream. toByteArray () ;}return null ;}}

In this simple method, we can perform an http request. The request result can be first read as binary data and then be operated accordingly, for example, we can get the source code of a website ..

In applications, we may return an xml file or a json string from the http server. We can obtain binary data in this way and then process the corresponding data.

Now we will introduce how to submit data to the http server through get and post.

First, we need an http server. I use Tomcat to describe it. First, we need to create a simple web application.

Let's take a 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] * @ CreateDate: [4:15:57, 2014-6-7] * @ UpdateUser: [hwb] * @ UpdateDate: [4:15:57] * @ UpdateRemark: [description of this modification] * @ Version: [v1.0] */public class UserServlet extends HttpServlet {/*** accept two parameters, print out */public void doGet (HttpServletRequest 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 );}}


Okay, let's create an Android app.

I created 4.4

Now let's only 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 callback method submits data to the http server via get * @ param path url * @ param userName uploaded userName * @ param passWord * @ return whether the upload is successful */public static boolean sendDataByGet (String path, string us ErName, 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 (5000); if (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 * @ param userName * @ param passWord * @ return result */public static boolean sendDataByPost (String 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); // you can set httpURLConnection to write data. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); // sets the http post request header information. The request data Content Type is httpURLConnection. setRequestProperty ("Content-Length", String. valueOf (arr. length); // set the header information of the http post request. The length of the request data OutputStream outputStream = httpURLConnection. getOutputStream (); outputStream. write (arr); // write data to the data stream if (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 ;}}


I learned a few knowledge points from them. Now let's summarize them.

1. first, the difference between GET and POST requests. we all know that GET is followed by parameters behind the URL path, while POST is placed in the Request body. I used a simple tool to intercept the request. You can check the comparison.

So what about Chinese?

See GET

See post


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + signature/Signature + signature/MSsyM + signature + 87Sw8fWsb3Tzai5/Signature + NDQseDC6y4uveK + 9re9t6i + signature/Signature = "brush: java; "> new String (value. getBytes ("ISO-8859-1"), "UTF-8 ");The specific code is as follows:

Now let's talk about the post method. We can directly specify the encoding method to get the correct data.

Okay, 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. optional; public class EncodingFilter implements Filter {public void doFilter (ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {// TODO Auto-generated method implements 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"); // The encoding method arg2.doFilter (httpServletRequest, httpServletResponse) must be set; }}} 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 ;}}



Okay. This is probably the case. If it is incorrect, please point it out!


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

It is best to use socket to upload files, because the http server has a limit on the size of the requested data file.

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.