Android:HttpGet与HttpPost

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(){
                        //生成一个请求对象
                        HttpGet httpGet=new HttpGet("http://www.baidu.com");
                        //生成一个客户端对象
                        HttpClient httpClient=new DefaultHttpClient();
                        InputStream inputStream=null;
                        try{
                            //使用http客户端发送请求对象
                            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(){
                        //创建url,这里是我自己搭建的一个服务器。
                        String url="http://10.8.198.200:8080/DemoServer/android/personalinfo.jsp";
                        //创建HttpPost对象
                        HttpPost httpPost=new HttpPost(url);
                        //生成一个客户端对象
                        HttpClient httpClient=new DefaultHttpClient();
                        // 如果传递参数个数比较多的话可以对传递的参数进行封装
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        NameValuePair  nameValuePair1=new BasicNameValuePair("User_ID","1");
                        //nameValuePair2=...
                        //nameValuePair3=...
                        //...

                        //将上面的nameValuePairs封装起来
                        params.add(nameValuePair1);
                        //params.add(nameValuePair2);
                        //params.add(nameValuePair3);
                        //...

                        //设置请求参数
                        try {
                            httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
                            //发送post请求
                            httpResponse=httpClient.execute(httpPost);
                            //如果服务器成功的返回响应
                            if(httpResponse.getStatusLine().getStatusCode()==200){
                                //获取服务器响应字符串
                                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 will
        // 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);
    }
}

日志:

点击HttpGet按钮时

08-04 00:48:52.195  11207-21599/com.example.litingdong.httptotaltest I/System.out﹕ <!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=Edge"><meta content="always" name="referrer"><meta name="theme-color" content="#2932e1"><link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /><link rel="search" type="application/opensearchdescription+xml" href="/content-search.xml" title="百度搜索" /><link rel="icon" sizes="any" mask href="//www.baidu.com/img/baidu.svg"><link rel="dns-prefetch" href="//s1.bdstatic.com"/><link rel="dns-prefetch" href="//t1.baidu.com"/><link rel="dns-prefetch" href="//t2.baidu.com"/><link rel="dns-prefetch" href="//t3.baidu.com"/><link rel="dns-prefetch" href="//t10.baidu.com"/><link rel="dns-prefetch" href="//t11.baidu.com"/><link rel="dns-prefetch" href="//t12.baidu.com"/><link rel="dns-prefetch" href="//b1.bdstatic.com"/><title>百度一下,你就知道</title><style index="index"  id="css_index">html,body{height:100%}html{overflow-y:auto}#wrapper{position:relative;_position:;min-height:100%}#head{padding-bottom:100px;text-align:center;*z-index:1}#ftCon{height:100px;position:absolute;bottom:44px;text-align:center;width:100%;margin:0 auto;z-index:0;overflow:hidden}#ftConw{width:720px;margin:0 auto}body{font:12px arial;text-align:;background:#fff}body,p,form,ul,li{margin:0;padding:0;list-style:none}body,form,#fm{position:relative}td{text-align:left}img{border:0}a{color:#00c}a:active{color:#f60}.bg{background-image:url(http://s1.bdstatic.com/r/www/cache/static/global/img/icons_45de3f02.png);background-repeat:no-repeat;_background-image:url(http://s1.bdstatic.com/r/www/cache/static/global/img/icons_15f748ea.gif)}.bg_tuiguang_browser{width:16px;height:16px;background-position:-600px 0;display:inline-block;vertical-align:text-bottom;font-style:normal;overflow:hidden;margin-right:5px}.bg_tuiguang_browser_big{width:56px;height:56px;position:absolute;left:10px;top:10px;background-position:-600px -24px}.bg_tuiguang_weishi{width:56px;height:56px;position:absolute;left:10px;top:10px;background-position:-672px -24px}.c-icon{display:inline-block;width:14px;height:14px;vertical-align:text-bottom;font-style normal;overflow:hidden;background:url(http://s1.bdstatic.com/r/www/cache/static/global/img/icons_45de3f02.png) no-repeat 0 0;_background-image:url(http://s1.bdstatic.com/r/www/cache/static/global/img/icons_15f748ea.gif)}.c-icon-triangle-down-blue{background-position:-480px -168px}.c-icon-chevron-unfold2{background-position:-504px -168px}#m{width:720px;margin:0 auto}#nv a,#nv b,.btn,#lk{font-size:14px}input{border:0;padding:0}#nv{height:19px;font-size:16px;margin:0 0 4px;text-align:left;text-indent:137px}.s_btn{width:95px;height:32px;padding-top:2px\9;font-size:14px;background-color:#ddd;background-position:0 -48px;cursor:pointer}.s_btn_h{background-position:-240px -48px}.s_btn_wr{width:97px;height:34px;display:inline-block;background-position:-120px -48px;*position:relative;z-index:0;vertical-align:top}#lk{margin:33px 0}#lk span{font:14px "宋体"}#lh{margin:16px 0 5px}#cp,#cp a{color:#666}#cp .c-icon-icrlogo{width:14px;height:17px;display:inline-block;overflow:hidden;background:url(http://s1.bdstatic.com/r/www/cache/static/global/img/icons_45de3f02.png) no-repeat;_background-image:url(http://s1.bdstatic.com/r/www/cache/static/global/img/icons_15f748ea.gif);background-position:-600px -96px;position:relative;top:3px}#shouji{margin-right:14px}#u{display:none}#c-tips-container{display:none}#wrapper{min-width:810px;height:100%;min-height:600px}#head{position:relative;padding-bottom:0;height:100%;min-height:600px}#head .head_wrapper{height:100%}#m{position:relative}#fm{padding-left:40px;top:-37px}#lh a{margin:0 10px}#lk{position:absolute;display:none;top:0;right:0}#nv{position:absolute;display:none;top:0;right:0}#lm{color:#666;width:100%;height:60px;margin-top:60px;line-height:15px;font-size:13px;position:absolute;top:0;left:0}#lm a{color:#666}#pad-version{line-height:40px}.s_ipt_wr.bg,.s_btn_wr.bg,#su.bg{background-image:none}.s_btn_wr{width:auto;

点击HttpPost按钮时

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"}

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-10-10 16:17:06

Android:HttpGet与HttpPost的相关文章

Android中使用HttpGet和HttpPost访问HTTP资源

需求:用户登录(name:用户名,pwd:密码) (一)HttpGet :doGet()方法//doGet():将参数的键值对附加在url后面来传递 [java] view plaincopy public String getResultForHttpGet(String name,String pwd) throws ClientProtocolException, IOException{ //服务器  :服务器项目  :servlet名称 String path="http://192.

HTTPClient模块的HttpGet和HttpPost

无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源. 1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象. 2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象. 3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理. 如果使用HttpPost方法提交HTTP POS

Android HttpGet() 请求简单入门实例

HttpClient httpclient = new DefaultHttpClient(); String url = "http://example.com"; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add( new BasicNameValuePair( "param", "value" ) ); URI uri =

java最简单的方式实现httpget和httppost请求

java实现httpget和httppost请求的方式多种多样,个人总结了一种最简单的方式,仅仅需几行代码,就能够完美的实现. 此处须要用到两个jar包,httpclient-4.3.1.jar.httpcore-4.3.jar,各位能够到网上自己下载,或者到我的附件里下载,以下先贴上httpget请求的代码: String url = ""; HttpGet request = new HttpGet(url); try { HttpResponse response = HttpC

转-浅谈HTTP-GET 、 HTTP-POST 和SOAP

原文链接:浅谈HTTP-GET . HTTP-POST 和SOAP 1.HTTP-GET 和 HTTP-POST HTTP-GET和HTTP-POST是标准协议,他们使用HTTP(超文本传输协议)谓词(谓词是指条件表达式的求值返回真或假的过程.)对参数金星编码并将参数作为名称/值对传递,还使用关联的请求语义.每个协议都包含一系列HTTP请求标头,HTTP请求标头及其他一些信息定义客户端向服务器请求哪些内容,哪个服务器用一系列HTTP响应标头和所请求的数据进行响应. HTTP-GET 使用 MIM

HttpGet和HttpPost

1 package net.blogjava.mobile; 2 3 import java.net.HttpURLConnection; 4 import java.util.ArrayList; 5 import java.util.List; 6 7 import org.apache.http.HttpResponse; 8 import org.apache.http.NameValuePair; 9 import org.apache.http.client.entity.UrlEn

.net在Controller里的方法添加[HttpGet]和[HttpPost]

前端用post过来,Controller就要用[HttpPost],前端用get,Controller就要用[HttpGet],或者不管前端用什么,Controller都不加这些. 前端用post $.ajax({ url: "/CommRecord/LockSendESMS", type: "post", data: { id: data.ID, isLock: isLock }, success: function (data) { } }); Controll

HttpGet和HttpPost请求

internal static string HttpPost(string Url, string postDataStr) { string retString = string.Empty; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/x-www-form

linux下HttpGet、HttpPost的C++实现

#include "HttpRequest.h" int main() { HttpRequest* Http = new HttpRequest; char* str = (char*)malloc(BUFSIZE); memset(str, 0, BUFSIZE); if(Http->HttpGet("http://www.baidu.com", str)) { printf("%s\n", str); } else { printf(