Get started with Android: Send http get and post requests

Source: Internet
Author: User
Document directory
  • Get:
HTTP request details have been explained in my blog:

Http://blog.csdn.net/xiazdong/article/details/7215296

I have encapsulated an HTTP request helper class in the http://blog.csdn.net/xiazdong/article/details/7725867, so it can be very simple to send get, post requests;

For example, httprequestutil. sendgetrequest (); is to send a GET request;



I. Core code

Core http get code:


(1) string value = urlencoder. encode (string value, "UTF-8 ");

(2) string Path = "http: // ../path? Key = "+ value;

(3) url = new URL (PATH); // The URL must be URL encoded;

(4) httpurlconnection con = (httpurlconnection) URL. openconnection ();

(5) con. setrequestmethod ("get ");

(6) con. setdooutput (true );

(7) outputstream out = con. getoutputstream ();

(8) Out. Write (byte [] BUF );

(9) int code = con. getresponsecode ();


Core http post code:


(1) string value = urlencoder. encode (string value, "UTF-8 ");

(2) byte [] Buf = ("Key =" + value). getbytes ("UTF-8 ");

(3) string Path = "http: // ../path ";

(4) url = new URL (PATH); // The URL here needs to be URL encoded;

(5) httpurlconnection con = (httpurlconnection) URL. openconnection ();

(6) con. setrequestmethod ("Post ");

(7) con. setdooutput (true );

(8) outputstream out = con. getoutputstream ();

(9) Out. Write (byte [] BUF );

(10) int code = con. getresponsecode ();

Ii. Get and post garbled Solutions

Get:

Add the following to doget:

String name = new string (request. getparameter ("name"). getbytes ("ISO-8859-1"), "UTF-8 ");

Post:

Add the following to dopost:


Request. setcharacterencoding ("UTF-8 ");

For more information, see my blog:

Http://blog.csdn.net/xiazdong/article/details/7217022

Iii. server code

Package Org. xiazdong. servlet; import Java. io. ioexception; import javax. servlet. servletexception; import javax. servlet. annotation. webservlet; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; @ webservlet ("/printservlet") public class printservlet extends httpservlet {protected void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {string name = new string (request. getparameter ("name "). getbytes ("ISO-8859-1"), "UTF-8"); string age = new string (request. getparameter ("Age "). getbytes ("ISO-8859-1"), "UTF-8"); system. out. println ("name:" + name + "\ n age:" + age);} protected void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {request. setcharacterencoding ("UTF-8"); system. out. println ("name:" + request. getparameter ("name") + "\ n age:" + request. getparameter ("Age "));}}

Iv. Android code

Add the following in androidmanifest. xml:

<uses-permission android:name="android.permission.INTERNET"/>

Mainactivity. Java

Package Org. xiazdong. network. submit; import Java. io. outputstream; import java.net. httpurlconnection; import java.net. URL; import java.net. urlencoder; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import android. widget. toast; public class mainactivity extends activity {priva Te edittext name, age; private button getbutton, postbutton; private onclicklistener listener = new onclicklistener () {@ overridepublic void onclick (view v) {try {If (getbutton = V) {/** because it is a GET request, you need to add the request parameters to the URL and perform URL encoding * url = http: // 192.168.0.103: 8080/Server/printservlet? Name = % E6 % 88% 91 & age = 20 * URL encoding is required here because the browser automatically performs URL encoding when submitting **/stringbuilder Buf = new stringbuilder ("http: // 192.168.0.103: 8080/Server/printservlet "); Buf. append ("? "); Buf. append ("name =" + urlencoder. encode (name. gettext (). tostring (), "UTF-8") + "&"); Buf. append ("age =" + urlencoder. encode (age. gettext (). tostring (), "UTF-8"); Url url = new URL (BUF. tostring (); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setrequestmethod ("get"); If (Conn. getresponsecode () = 200) {toast. maketext (mainactivity. this, "Get submitted", toast. length_short ). show ();} else toast. maketext (mainactivity. this, "Get submission failed", toast. length_short ). show ();} If (postbutton = V) {/** if it is a POST request, the request parameters are placed in the Request body, * name = % E6 % 88% 91 & age = 12 ***/stringbuilder Buf = new stringbuilder (); Buf. append ("name =" + urlencoder. encode (name. gettext (). tostring (), "UTF-8") + "&"); Buf. append ("age =" + urlencoder. encode (age. gettext (). tostring (), "UTF-8"); byte [] DATA = Buf. tostring (). getbytes ("UTF-8"); Url url = new URL ("http: // 192.168.0.103: 8080/Server/printservlet"); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setrequestmethod ("Post"); Conn. setdooutput (true); // you must add outputstream out = conn to output data. getoutputstream (); out. write (data); If (Conn. getresponsecode () = 200) {toast. maketext (mainactivity. this, "Get submitted", toast. length_short ). show ();} else toast. maketext (mainactivity. this, "Get submission failed", toast. length_short ). show () ;}} catch (exception e) {}};@ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); name = (edittext) This. findviewbyid (R. id. name); age = (edittext) This. findviewbyid (R. id. age); getbutton = (button) This. findviewbyid (R. id. getbutton); postbutton = (button) This. findviewbyid (R. id. postbutton); getbutton. setonclicklistener (listener); postbutton. setonclicklistener (listener );}}

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.