Android:httpget and HttpPost

Source: Internet
Author: User



Androidmanifest.xml


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



Activity_main.xml

<relativelayout 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: paddingleft= "@dimen/activity_horizontal_margin"    android:paddingright= "@dimen/activity_horizontal_margin"    android:paddingtop= "@dimen/activity_vertical_margin"    android:paddingbottom= "@dimen/activity_vertical_ Margin "tools:context=". Mainactivity ">    <button        android:id=" @+id/httpgetbutton "        android:layout_width=" Match_parent "        android:layout_height= "wrap_content"        android:text= "HttpGet"/>    <button        android:id= "@+ Id/httppostbutton "        android:layout_width=" match_parent "        android:layout_height=" Wrap_content        " android:text= "HttpPost"        android:layout_below= "@+id/httpgetbutton"        /></relativelayout>


Mainactivity.java

Import Android.support.v7.app.actionbaractivity;import Android.os.bundle;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.widget.button;import org.apache.http.HttpEntity; Import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.client.clientprotocolexception;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 Org.apache.http.util.entityutils;import org.w3c.dom.Entity; Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.unsupportedencodingexception;import Java.util.ArrayList;import Java.util.list;public class Mainactivity extends Actionbaractivity {private Button httpgetbutton=nUll    Private Button Httppostbutton=null;    Private HttpResponse Httpresponse=null;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        httpgetbutton= (Button) Findviewbyid (R.id.httpgetbutton);        httppostbutton= (Button) Findviewbyid (R.id.httppostbutton); Httpgetbutton.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {New Thread () {@Override public void run () {//Build                        A Request object HttpGet httpget=new httpget ("http://www.baidu.com");                        Generate a Client object HttpClient httpclient=new defaulthttpclient ();                        InputStream Inputstream=null; try{//Use HTTP client to send Request object Httpresponse=httpclient.execute (HTTpget);                            Httpentity entity=httpresponse.getentity ();                            Inputstream=entity.getcontent ();                            BufferedReader reader=new BufferedReader (New InputStreamReader (InputStream));                            String result= "";                            String Line;                            while ((Line=reader.readline ())!=null) {result=result+line;                        } System.out.println (Result);                        }catch (Exception e) {e.printstacktrace ();            }}}.start ();        }        });  Httppostbutton.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {New Thread () {@Override public void run () {//Create           URL, this is a server I built myself.             String url= "http://10.8.198.200:8080/DemoServer/android/personalinfo.jsp";                        Create HttpPost Object HttpPost httppost=new httppost (URL);                        Generate a Client object HttpClient httpclient=new defaulthttpclient (); The passed parameters can be encapsulated list<namevaluepair> params = new arraylist<namevaluepair> If the number of passed arguments is more than one (                        );                        Namevaluepair namevaluepair1=new Basicnamevaluepair ("user_id", "1"); Namevaluepair2= ...//namevaluepair3= ...//the above                        The Namevaluepairs package up Params.add (NAMEVALUEPAIR1);                        Params.add (NAMEVALUEPAIR2);                        Params.add (NAMEVALUEPAIR3); ...//Set request parameter try {httppost.setentity (new Urlen CoDedformentity (params, "utf-8"));                            Send POST request Httpresponse=httpclient.execute (HttpPost);                                If the server succeeds in returning the response if (Httpresponse.getstatusline (). Getstatuscode () ==200) {                                Gets the server response string result= entityutils.tostring (httpresponse.getentity ());                            SYSTEM.OUT.PRINTLN (result);                        }} catch (Unsupportedencodingexception e) {e.printstacktrace ();                        } catch (Clientprotocolexception e) {e.printstacktrace ();                        } catch (IOException e) {e.printstacktrace ();            }}}.start ();    }        }); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menU        This adds items to the action bar if it is present.        Getmenuinflater (). Inflate (R.menu.menu_main, menu);    return true; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here.  The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent        Activity in Androidmanifest.xml.        int id = item.getitemid ();        Noinspection simplifiableifstatement if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); }}

Log:

When you click the HttpGet button

08-04 00:48:52.195 11207-21599/com.example.litingdong.httptotaltest i/system.out:<! DOCTYPE html><!--STATUS ok-->

When you click the HttpPost button

08-04 00:49:52.493  11207-22973/com.example.litingdong.httptotaltest i/system.out:{"User_phone": 15001337861, " USER_ID ": 1," User_sex ": 1," User_password ":" qwerty1234 "," User_birthday ":" 2015-5-17 "," user_name ":" Li "}












Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android:httpget and HttpPost

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.