Android HTTP Programming notes

Source: Internet
Author: User

Template file


<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:id=" @+id/container "android:orientation=" vertical "android:layout_width=" match _parent "android:layout_height=" match_parent "><textview android:id=" @+id/tv_user "android:layout_width=" WR Ap_content "android:layout_height=" wrap_content "android:text=" user name "/><edittext android:id=" @+id/et_use R "android:layout_width=" Fill_parent "android:layout_height=" wrap_content "android:hint=" please fill in the user name "/><Text View android:id= "@+id/tv_pass" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Andro id:text= "Password"/><edittext android:id= "@+id/et_pass" android:layout_width= "Fill_parent" android:layout_he ight= "wrap_content" android:hint= "please fill in the password"/><button android:id= "@+id/button" android:layout_width= "Fill_ Parent "android:layout_height=" Wrap_content "    android:text= "Get Login" android:onclick= "GetLogin"/><button android:id= "@+id/button2" Android:layout_ Width= "Fill_parent" android:layout_height= "wrap_content" android:text= "Post Login" android:onclick= "PostLogin"/&G T;<button android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "HttpClientGet Login "android:onclick=" Clientgetlogin "/><button android:layout_width=" fill_parent "Android:layout_height" = "Wrap_content" android:text= "httpclientpost Login" android:onclick= "Clientpostlogin"/></linearlayout>



Mainactivity



Package Com.http.action;import Com.login.service.loginservice;import Android.app.activity;import Android.app.actionbar;import Android.app.fragment;import Android.os.bundle;import Android.os.Handler;import Android.os.message;import Android.view.layoutinflater;import Android.view.menu;import Android.view.MenuItem; Import Android.view.view;import Android.view.viewgroup;import Android.widget.edittext;import Android.widget.textview;import Android.widget.toast;import Android.os.build;public class MainActivity extends Activity {protected static final int login_success = 1;protected static final int login_error = 2;private EditText et_user ;p rivate EditText et_pass;private Handler Handler = new Handler () {public void Handlemessage (Android.os.Message Message) { Switch (message.what) {case LOGIN_SUCCESS:Toast.makeText (mainactivity.this, (String) message.obj, Toast.length_short ). Show (); Break;case LOGIN_ERROR:Toast.makeText (mainactivity.this, "Login Failed", Toast.length_short). Show (); break;}}; @OverrideproteCTED void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity _main); et_user = (EditText) Findviewbyid (r.id.et_user); et_pass = (EditText) Findviewbyid (R.id.et_pass);} /** * Login * @param view */public void GetLogin (view view) {Final String user = Et_user.gettext (). toString (). Trim (); final Str ing pass = et_pass.gettext (). toString (). Trim (); new Thread () {public void run () {String res = loginservice.bygetlogin (user , pass), if (res! = NULL) {message msg = new Message (); msg.what = Login_success;msg.obj = Res;handler.sendmessage (msg);} El SE {message msg = new Message (); msg.what = Login_error;handler.sendmessage (msg);}}}. Start ();} /** * Post Method submitted * @param view */public void Postlogin (view view) {Final String user = Et_user.gettext (). toString (). Trim (); f Inal String pass = Et_pass.gettext (). toString (). Trim (); new Thread () {public void run () {String Text = Loginservice.bypostlogin (user, pass), if (text! = null) {message msg = new Message (); msg.what = Login_sucCess;msg.obj = Text;handler.sendmessage (msg);} else {message msg = new Message (); msg.what = Login_error;handler.sendmessage (msg);}}}. Start ();} /** * Client Get login * @param view */public void Clientgetlogin (view view) {Final String user = Et_user.gettext (). Tostrin g (). Trim (); final String pass = Et_pass.gettext (). toString (). Trim (); new Thread () {public void run () {String res = Loginservice.httpclientgetlogin (user, pass); if (res! = NULL) {message msg = new Message (); msg.what = Login_success;msg.ob j = res;handler.sendmessage (msg);} else {message msg = new Message (); msg.what = Login_error;handler.sendmessage (msg);}}}. Start ();} /** * Client Post login * @param view */public void Clientpostlogin (view view) {Final String user = Et_user.gettext (). tostr ing (). Trim (); final String pass = Et_pass.gettext (). toString (). Trim (); new Thread () {public void run () {String res = Loginservice.httpclientpostlogin (user, pass); if (res! = NULL) {message msg = new Message (); msg.what = LOGIN_SUCCESS;MSG.O BJ = Res;handler.sEndmessage (msg);} else {message msg = new Message (); msg.what = Login_error;handler.sendmessage (msg);}}}. Start ();}}


Loginservice


Package Com.login.service;import Java.io.inputstream;import Java.io.outputstream;import Java.io.unsupportedencodingexception;import Java.net.httpurlconnection;import java.net.MalformedURLException; Import Java.net.url;import java.util.arraylist;import Java.util.list;import Org.apache.http.httpconnection;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import org.apache.http.client.HttpClient; Import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;import Com.stream.utils.stream;public class LoginService {/** * submitted by Get method * @param user * @param pass * @return */static public string Bygetlogin (string user, String pass) {string path = "Http://19 2.168.0.105/index.php?user= "+user+" &pass= "+pass;try {URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.opEnconnection (); Conn.setreadtimeout () Conn.setrequestmethod ("GET"); int code = Conn.getresponsecode (); SYSTEM.OUT.PRINTLN (code), if (code = =) {InputStream is = Conn.getinputstream (); String Text = stream.istostring (is); return text;} else {return null;}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace (); return null;}}  /** * Submit via Post * @param user * @param pass * @return */static public string Bypostlogin (string user, String pass) {string Path = "http://192.168.0.105/index.php"; try {URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("POST"); String data = "user=" +user+ "&pass=" +pass;conn.setrequestproperty ("Content-type", "application/ X-www-form-urlencoded "); Conn.setrequestproperty (" Content-length ", data.length () +" "); Conn.setdooutput (true); O Utputstream OS = Conn.getoutputstream (); Os.write (Data.getbytes ()); int code = Conn.getresponsecode (); if (code = = 200) { InputStream is = Conn.getinputstream (); RETUrn stream.istostring (IS); } else {return null;}} catch (Exception e) {e.printstacktrace (); return null;}} /** * with HttpClient get submit * @param user * @param pass * @return */static public string Httpclientgetlogin (string user, Str ing pass) {String path = "http://192.168.0.105/index.php?user=" +user+ "&pass=" +pass;try {HttpClient client = new Defaulthttpclient (); HttpGet get = new HttpGet (path); HttpResponse response = Client.execute (get), int code = Response.getstatusline (). Getstatuscode (); if (code = = 200) { InputStream is = Response.getentity (). getcontent (); String Text = stream.istostring (is); return text;} return null;} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace (); return null;}} /** * HttpClient Post Method submitted * @param user * @param pass * @return */static public string Httpclientpostlogin (string user, S Tring Pass) {String path = "http://192.168.0.105/index.php"; HttpClient client = new Defaulthttpclient (); HttpPost post = new HttpPost (path); List<namevaluepair> parAmeters = new arraylist<namevaluepair> ();p Arameters.add (New Basicnamevaluepair ("user", user);p Arameters.add ( New Basicnamevaluepair ("Pass", pass)), try {post.setentity (new urlencodedformentity (Parameters, "UTF-8")); HttpResponse response = Client.execute (post); int code = Response.getstatusline (). Getstatuscode (); if (code = = 200) { InputStream is = Response.getentity (). getcontent (); String Text = stream.istostring (is); return text;} return null;} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace (); return null;}}}




Stream converts input flow to string


Package Com.stream.utils;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.inputstream;public class Stream {/** * turns an input stream into a string * @param is * @return * @throws ioexception */static public Str ing istostring (InputStream is) throws Ioexception{bytearrayoutputstream BAOs = new Bytearrayoutputstream (); int len = 0;by te[] buffer = new Byte[1024];while (len = is.read (buffer))! =-1) {baos.write (buffer);} Byte[] result = Baos.tobytearray (); Is.close (); Baos.close (); return new String (result);}}




Remember manifest file permissions

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


Android HTTP Programming notes

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.