Android中的get和post

一、需要用到的场景

在jQuery中使用$.post()就可以方便的发起一个post请求,在android程序中有时也要从服务器获取一些数据,就也必须得使用post请求了。

 

二、需要用到的主要类

在android中使用post请求主要要用到的类是HttpPost、HttpResponse、EntityUtils

 

三、主要思路

1、创建HttpPost实例,设置需要请求服务器的url。

2、为创建的HttpPost实例设置参数,参数设置时使用键值对的方式用到NameValuePair类。

3、发起post请求获取返回实例HttpResponse

4、使用EntityUtils对返回值的实体进行处理(可以取得返回的字符串,也可以取得返回的byte数组)

代码也比较简单,注释也加上了,就直接贴出来了

package com.justsy.url;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.protocol.HTTP;

import org.apache.http.util.EntityUtils;

import android.app.Activity;

import android.os.Bundle;

public class HttpURLActivity extends Activity {    

    @Override

    public void onCreate(Bundle savedInstanceState) {        

         super.onCreate(savedInstanceState);        

         System.out.println(“start url…”);        

         String url = “http://192.168.2.112:8080/JustsyApp/Applet“;

        // 第一步,创建HttpPost对象

         HttpPost httpPost = new HttpPost(url);

        // 设置HTTP POST请求参数必须用NameValuePair对象

        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair(“action”, “downloadAndroidApp”));

        params.add(new BasicNameValuePair(“packageId”, “89dcb664-50a7-4bf2-aeed-49c08af6a58a”));

        params.add(new BasicNameValuePair(“uuid”, “test_ok1″));

        HttpResponse httpResponse = null;

        try {

            // 设置httpPost请求参数

            httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

            httpResponse = new DefaultHttpClient().execute(httpPost);

            //System.out.println(httpResponse.getStatusLine().getStatusCode());

            if (httpResponse.getStatusLine().getStatusCode() == 200) {

                // 第三步,使用getEntity方法活得返回结果

                String result = EntityUtils.toString(httpResponse.getEntity());

                System.out.println(“result:” + result);

                T.displayToast(HttpURLActivity.this, “result:” + result);

            }

        } catch (ClientProtocolException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        System.out.println(“end url…”);

        setContentView(R.layout.main);

    } }

ADD:使用HttpURLConnection 进行post请求

String path = “http://192.168.2.115:8080/android-web-server/httpConnectServlet.do?PackageID=89dcb664-50a7-4bf2-aeed-49c08af6a58a”;

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod(“POST”);

conn.setConnectTimeout(5000);

System.out.println(conn.getResponseCode());

 

 

============================================================================================================================

 

通过get和post方式向服务器发送请求

首先说一下get和post的区别
get请求方式是将提交的参数拼接在url地址后面,例如http://www.baidu.com/index.jsp?num=23&jjj=888; 但是这种形式对于那种比较隐私的参数是不适合的,而且参数的大小也是有限制的,一般是1K左右吧,对于上传文件 就不是很适合。

post请求方式是将参数放在消息体内将其发送到服务器,所以对大小没有限制,对于隐私的内容也比较合适。 如下Post请求
POST /LoginCheck HTTP/1.1

Accept: text/html, application/xhtml+xml, */* Referer: http://192.168.2.1/login.asp

Accept-Language: zh-CN

User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)

Content-Type: application/x-www-form-urlencoded Accept-Encoding: gzip, deflate Host: 192.168.2.1 Content-Length: 39

Connection: Keep-Alive

Cache-Control: no-cache

Cookie: language=en
Username=admin&checkEn=0&Password=admin   //参数位置

在android中用get方式向服务器提交请求:
在android模拟器中访问本机中的tomcat服务器时,注意:不能写localhost,因为模拟器是一个单独的手机系统,所以要写真是的IP地址。 否则无法访问到服务器。
//要访问的服务器地址,下面的代码是要向服务器提交用户名和密码,提交时中文先要经过URLEncoder编码,因为模拟器默认的编码格式是utf-8 //而tomcat内部默认的编码格式是ISO8859-1,所以先将参数进行编码,再向服务器提交。

private String address = “http://192.168.2.101:80/server/loginServlet”;
public boolean get(String username, String password) throws Exception {

  username = URLEncoder.encode(username);

  // 中文数据需要经过URL编码

  password = URLEncoder.encode(password);

  String params = “username=” + username + “&password=” + password;

  //将参数拼接在URl地址后面

  URL url = new URL(address + “?” + params);

  //通过url地址打开连接

  HttpURLConnection conn = (HttpURLConnection) url.openConnection();

  //设置超时时间

  conn.setConnectTimeout(3000);

  //设置请求方式

  conn.setRequestMethod(“GET”);

  //如果返回的状态码是200,则一切Ok,连接成功。

  return conn.getResponseCode() == 200;

}

在android中通过post方式提交数据。
public boolean post(String username, String password) throws Exception {

  username = URLEncoder.encode(username);

  // 中文数据需要经过URL编码

  password = URLEncoder.encode(password);

  String params = “username=” + username + “&password=” + password;

  byte[] data = params.getBytes();

  URL url = new URL(address);

  HttpURLConnection conn = (HttpURLConnection) url.openConnection();

  conn.setConnectTimeout(3000);

  //设置请求方式为POST

  conn.setRequestMethod(“POST”);

  //设置post请求必要的请求头

  conn.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);

  // 请求头, 必须设置

  conn.setRequestProperty(“Content-Length”, data.length + “”);

  // 注意是字节长度, 不是字符长度

  conn.setDoOutput(true);

  // 准备写出

  conn.getOutputStream().write(data);

  // 写出数据

  return conn.getResponseCode() == 200;

}

posted @ 2013-12-06 09:59  笨猪笨笨  阅读(385)  评论(0编辑  收藏  举报