Using HttpURLConnection to request data using the Get or POST method

Source: Internet
Author: User
Tags gettext

To submit a request using URLConnection:

1. Create a URLConnection object by calling the URL object OpenConnection () method

2. Set urlconnection parameters and normal request properties

3. If you just send a Get method request, use the Connet method to establish the actual connection between the remote resources, and if you send a post-mode request, you need to get the output stream for the URLConnection instance to send the request parameters.

4. The remote resource becomes available, and the program can access the remote resource's header field or read the data from the remote resources through the input stream.

Submit data to server side (there is garbled in Chinese):

Requirements: Demonstrates how to send a GET request, a POST request, and a response from a Web site to a Web site.

Server-side

Serlvet for impersonating User login

public class Loginservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {String username =  Request.getparameter ("username"); String Password = request.getparameter ("password"); System.out.println ("name =" +username); SYSTEM.OUT.PRINTLN ("password =" +password), if ("Lisi". Equals (username) && "123". Equals (password)) { Response.getoutputstream (). Write ("Success". GetBytes ());} Else{response.getoutputstream (). Write ("Failed". GetBytes ());}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (request, Response);}}

In the Address bar, enter:

Http://localhost:8080/ServerDemo1/servlet/LoginServlet?username=lisi&password=123

Page return:


Page returns the login success information: success. View the source file for this page is also just a: success

Requirements: From the client requests the data to the service side, the service side's information returns to the service side.

Client
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:orientation= "vertical" >    <edittext android:layout_width= "match_parent"        android:layout _height= "Wrap_content"        android:hint= "Please enter user name"        android:id= "@+id/et_username"/>    <edittext Android:layout_width= "Match_parent"        android:layout_height= "wrap_content"        android:hint= "Please enter your password"        Android:id= "@+id/et_password"/>    <button android:layout_width= "match_parent"        android:layout_ height= "Wrap_content"        android:text= "Get Submit Method"        android:onclick= "Doget"/>    <button android: Layout_width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "post submission Method"        android:onclick= "DoPost"/></linearlayout>

Tool class:

Netutil.java

public class Netutil {private static final String TAG = "Netutil";/** * Login with Get * @param username * @param password * @  Return login status */public static string Loginofget (string username,string password) {HttpURLConnection conn = null;try {string data = "Username=" +username+ "&password=" +password; URL url = new URL ("Http://10.3.5.154:8080/ServerDemo1/servlet/LoginServlet?") +DATA); conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET");// Get and post must be fully capitalized conn.setconnecttimeout (10000);//timeout for connection conn.setreadtimeout (5000);//timeout for read data int responsecode = Conn.getresponsecode (); if (responsecode==200) {//access succeeded, the data information of the page through which the stream was taken inputstream is = Conn.getinputstream (); String status = Getstringfrominputstream (is); return status;} ELSE{LOG.I (TAG, "Access failed:" +responsecode);}} catch (Exception e) {e.printstacktrace ();} finally{if (Conn!=null) {conn.disconnect ();//release link}}return null;} /** * Use Post submission method * @param username * @param password * @return */public static string Loginofpost (string username, string PAssword) {HttpURLConnection conn = null;try {URL url = new URL ("Http://10.3.5.154:8080/ServerDemo1/servlet/LoginServlet "); conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod (" GET ");// Get and post must be fully capitalized conn.setconnecttimeout (10000);//timeout for connection conn.setreadtimeout (5000);//timeout for read data conn.setdooutput (TRUE) ;//You must set this method to allow output//conn.setrequestproperty ("Content-length", 234);//Set Request message header to set parameters for multiple//post requests String data = "Username=" +username+ "&password=" +password;outputstream out = Conn.getoutputstream (); Out.write (Data.getBytes ()); O Ut.flush (); Out.close (); int responsecode = Conn.getresponsecode (); if (responsecode==200) {//Access succeeded, Data information for a page that is streamed inputstream is = Conn.getinputstream (); String status = Getstringfrominputstream (is); return status;} ELSE{LOG.I (TAG, "Access failed:" +responsecode);}} catch (Exception e) {e.printstacktrace ();} finally{if (Conn!=null) {conn.disconnect ();//release link}}return null;} /** * Returns a string message through a byte input stream * @param is * @return * @throws ioexception */private static string getstringfrominputstrEAM (InputStream is) throws IOException {Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); byte[] buffer = new byte[ 1024];int Len=0;while ((len=is.read (buffer))!=-1) {baos.write (buffer, 0, Len);} Is.close (); String status = Baos.tostring ();//Convert the data in the stream into a string, using the encoding: Utf-8baos.close (); return status;}}

Java code:

Mainactivity.java

public class Mainactivity extends Activity {private EditText et_username;private EditText et_password;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); et_username = (EditText) Findviewbyid (r.id.et_username); Et_password = (EditText) Findviewbyid (R.id.et_password);} Get submission method public void doget (view view) {final string username = Et_username.gettext (). toString (). Trim (); final string Password = Et_password.gettext (). toString (). Trim (); New Thread (New Runnable () {@Overridepublic void Run () {// Use get to crawl the data final String status = Netutil.loginofget (username, password);//Perform the task in the main thread runonuithread (new Runnable () {@ overridepublic void Run () {///is the operation of Toast.maketext (mainactivity.this, status, 0) in the main thread. Show ();});}). Start ();} Post submission method public void DoPost (view view) {final string username = Et_username.gettext (). toString (). Trim (); final string Password = Et_password.gettext (). toString (). Trim (); New Thread (New Runnable () {@Overridepublic void Run () {final String status = Netutil.loginofpost (Username,password); Runonuithread (new Runnable () {@ overridepublic void Run () {Toast.maketext (mainactivity.this, status, 0). Show ();}});}). Start ();}}

Run:

Use Get or post submission method

Submits data from the client to the server side, returning the server-side information to the client.


But the above code has serious Chinese garbled problem :

Simple garbled Analysis:


Submit data to server side (solve Chinese garbled) recommended:

Understand the cause of garbled, this time we analyze the steps to solve garbled:

( hold : Ensure that the code used by the client and server must be consistent )

1. Modify the client code:

Modify netutil. Java


Modified code:

/*** Urlencoder.encode (string s, String charsetname) encodes the Chinese parameter in the URL to resolve garbled */string data = "Username=" + Urlencoder.encode (username, "utf-8") + "&password=" +urlencoder.encode (password, "Utf-8");    URL url =  new URL ("Http://10.3.5.154:8080/ServerDemo1/servlet/LoginServlet?") +DATA); conn = (httpurlconnection) url.openconnection ();

2. Modify the server-side code:

Modify Loginservlet.java

:

Modified code:

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { String username =  Request.getparameter ("username");//The parameter that is requested is the encoding that is used: iso8859-1string password = Request.getparameter ("password");//Use iso8859-1 encoding to reverse the name, convert it into a byte array, and then convert the data using UTF-8 encoding, String username = new String ( Username.getbytes ("Iso8859-1"), "Utf-8");p Assword = new String (password.getbytes ("iso8859-1"), "Utf-8"); System.out.println ("name =" +username); SYSTEM.OUT.PRINTLN ("password =" +password), if ("Lisi". Equals (username) && "123". Equals (password)) { Response.getoutputstream (). Write ("Login succeeded". GetBytes ("Utf-8")); Else{response.getoutputstream (). Write ("Login failed". GetBytes ("Utf-8"));}}

3. Running result (successfully solve garbled problem):

Complete code (garbled problem resolved):

Server-side:

public class Loginservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {String username =  Request.getparameter ("username");//The request came over the parameters, The encoding used is: iso8859-1string password = request.getparameter ("password"),//The name is reversed with iso8859-1 encoding, converted to a byte array, The data is then converted using UTF-8 encoding, the string username = new String (Username.getbytes ("iso8859-1"), "Utf-8");p Assword = new String ( Password.getbytes ("Iso8859-1"), "Utf-8"); System.out.println ("name =" +username); SYSTEM.OUT.PRINTLN ("password =" +password), if ("Lisi". Equals (username) && "123". Equals (password)) {/** * GetBytes by default, ISO8859-1 encoding is used, but if no current character in the Discovery Code table * will use the default encoding GBK under the current system; */response.getoutputstream (). Write ("Login succeeded". GetBytes ("Utf-8")); Else{response.getoutputstream (). Write ("Login failed". GetBytes ("Utf-8"));}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (request, Response);}}

Client code:

Tool class:

public class Netutil {private static final String TAG = "Netutil";/** * Login with Get * @param username * @param password * @ Return login status */public static string Loginofget (string username,string password) {HttpURLConnection conn = null;try {/** * U Rlencoder.encode (string s, String charsetname) encodes the Chinese parameter in the URL to resolve garbled */string data = "Username=" +urlencoder.encode ( Username, "utf-8") + "&password=" +urlencoder.encode (password, "Utf-8");//get way, url is directly at the back of the URL URL of the stitching address = new URL (" Http://10.3.5.154:8080/ServerDemo1/servlet/LoginServlet? " +DATA); conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET");// Get and post must be fully capitalized conn.setconnecttimeout (10000);//timeout for connection conn.setreadtimeout (5000);//timeout for read data int responsecode = Conn.getresponsecode (); if (responsecode==200) {//access succeeded, the data information of the page through which the stream was taken inputstream is = Conn.getinputstream (); String status = Getstringfrominputstream (is); return status;} ELSE{LOG.I (TAG, "Access failed:" +responsecode);}} catch (Exception e) {e.printstacktrace ();} finally{if (Conn!=null) {Conn.diSconnect ();//release link}}return null;} /** * Use Post submission method * @param username * @param password * @return */public static string Loginofpost (string username, string Password) {HttpURLConnection conn = null;try {//post The requested URL address is a stream-written url url = new URL ("http://10.3.5.154:8080/ Serverdemo1/servlet/loginservlet "); conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod (" GET "); /get and post must be fully capitalized Conn.setconnecttimeout (10000),//timeout for connection conn.setreadtimeout (5000),//timeout for read data Conn.setdooutput (true )///You must set this method to allow output//conn.setrequestproperty ("Content-length", 234);//Set Request message header to set parameters for multiple//post requests String data = "Username= The "+username+" &password= "+password;//obtains an output stream for writing data to the server, which, by default, does not allow output to the server outputstream out = Conn.getoutputstream (); Out.write (Data.getbytes ()); Out.flush (); Out.close (); int responsecode = Conn.getresponsecode (); if (responsecode==200) {//access succeeded, the data information of the page through the stream inputstream is = Conn.getinputstream (); String status = Getstringfrominputstream (is); return status;} ELSE{LOG.I (TAG, "Access failed:" +responsecode);}} catch (Exception e) {e.printstacktrace ();} finally{if (Conn!=null) {conn.disconnect ();//release link}}return null;} /** * Returns a string message through a byte input stream * @param is * @return * @throws ioexception */private static string Getstringfrominputstream (input  Stream is) throws IOException {Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); byte[] buffer = new Byte[1024];int Len=0;while ((len=is.read (buffer))!=-1) {baos.write (buffer, 0, Len);} Is.close (); String status = Baos.tostring ();//Convert the data in the stream into a string, using the encoding: Utf-8baos.close (); return status;}}

The Mainactivity.java class does not change the same as above.

Using HttpURLConnection to request data using the Get or POST method

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.