Android Http get post请求

本文介绍了在Android平台上如何使用HTTP GET和POST方法执行请求,并提供了详细的代码示例。主要内容包括请求发送、参数传递及响应解析,适用于Android开发人员理解和实现网络请求。

声明:文章系转载,原文链接不祥。

——————————————————————————————————————


首先我们先了解下Get请求和Post请求的区别:

表单提交中get和 post方式的区别有5点:

  1. get是从服务器上获取数据,post是向服务器传送数据。
  2. get是把参数数据队列加到提交表单的 ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。post是通过HTTP post机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。
  3. 对于get方式,服务器端用 Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据。
  4. get 传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。
  5. get安全性非常低,post安全性较高。

一、HttpClinet方式

1、HTTP GET 示例:

public class TestHttpGetMethod{  
    public void get(){  
        BufferedReader in = null;  
        try{  
            HttpClient client = new DefaultHttpClient();  
            HttpGet request = new HttpGet();  
            request.setURI("http://w26.javaeye.com");  
            HttpResponse response = client.execute(request);   
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));     
            StringBuffer sb = new StringBuffer("");   
            String line = "";  
            String NL = System.getProperty("line.separator");  
            while((line = in.readLine()) != null){  
                sb.append(line + NL); 

            }  
            in.close();  
            String page = sb.toString();  
            Log.i(TAG, page);  
        }catch(Exception e){  
            Log.e(TAG,e.toString())  
        }finally{  
            if(in != null){  
                try{  
                    in.close();  
                }catch(IOException ioe){  
                    Log.e(TAG, ioe.toString());  
                }  
            }  
        }  
    }  
}

带参数的 HTTP GET: 
HttpGet request = new HttpGet("http://www.baidu.com/s?wd=amos_tl");  
client.execute(request);

2、HTTP POST 示例:

public class TestHttpPostMethod{  
    public void post(){  
        BufferedReader in = null;  
        try{  
            HttpClient client = new DefaultHttpClient();  
            HttpPost request = new HttpPost("http://localhost/upload.jsp");   
            List<NameValuePair> postParams = new ArrayList<NameValuePair>();  
            postParams.add(new BasicNameValuePair("filename", "sex.mov"));  
            UrlEncodeFormEntity formEntity = new UrlEncodeFormEntity(postParams);  
            request.setEntity(formEntity);  
            HttpResponse response = client.execute(request);  
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));     
            StringBuffer sb = new StringBuffer("");   
            String line = "";  
            String NL = System.getProperty("line.separator");  
            while((line = in.readLine()) != null){  
                sb.append(line + NL);  
            }  
            in.close();  
            String result = sb.toString();  
            Log.i(TAG, result );  
        }catch(Exception e){  
            Log.e(TAG,e.toString())  
        }finally{  
            if(in != null){  
                try{  
                    in.close();  
                }catch(IOException ioe){  
                    Log.e(TAG, ioe.toString());  
                }  
            }  
        }  
    } 
}

三、HttpURLConnection 方式

URL url = null;
HttpURLConnection conn = null;
InputStream in = null;
OutputStream out = null;
byte[] data ="测试字符串".getBytes();
try{
   url =new URL("www.xxx.com/servlet");
   conn = (HttpURLConnection) url.openConnection();

   //设置连接属性
   conn.setDoOutput(true);// 使用 URL 连接进行输出
   conn.setDoInput(true);// 使用 URL 连接进行输入
   conn.setUseCaches(false);// 忽略缓存
   conn.setConnectTimeout(30000);//设置连接超时时长,单位毫秒
   conn.setRequestMethod("POST");//设置请求方式,POST or GET,注意:如果请求地址为一个servlet地址的话必须设置成POST方式

//设置请求头
  conn.setRequestProperty("Accept", "*/*");
  conn.setRequestProperty("Connection", "Keep-Alive");
  conn.setRequestProperty("Accept-Charset", "utf-8");
  if (data != null) {
     out = conn.getOutputStream();
     out.write(data);
  }
  int code = conn.getResponseCode();
  if(code ==200){
     in = conn.getInputStream();// 可能造成阻塞
     long len = conn.getContentLength();
     byte[] bs = new byte[(int) len];//返回结果字节数组
     int all = 0;
  int dn = 0;
     while ((dn = in.read(bs, all, 1)) > 0) {
       all += dn;
       if (all == len) {
       break;
       }
     }
  }
}

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

那么接下来让我们看看在Android平台开发中如何执行一个Post请求:

以下是代码示例:

package com.jixuzou.search;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class mian extends Activity {
        /** Called when the activity is first created. */
        private Button btnTest;
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                btnTest = (Button) findViewById(R.id.Button01);
                btnTest.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                                getWeather();
                        }
                });
        }
        private void getWeather(){
                try {
                        final String SERVER_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather"; // 定义需要获取的内容来源地址
                        HttpPost request = new HttpPost(SERVER_URL); // 根据内容来源地址创建一个Http请求
                        List params = new ArrayList();
                        params.add(new BasicNameValuePair("theCityCode", "长沙")); // 添加必须的参数
                        params.add(new BasicNameValuePair("theUserID", "")); // 添加必须的参数
                        request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 设置参数的编码
                        HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 发送请求并获取反馈
			// 解析返回的内容
                        if (httpResponse.getStatusLine().getStatusCode() != 404)
                        {
                                String result = EntityUtils.toString(httpResponse.getEntity());
                                System.out.println(result);
                        }
                } catch (Exception e) {
                }
        }
}


代码下载地址: https://pan.quark.cn/s/bc087ffa872a "测控电路课后习题详解"文件.pdf是一份极具价值的学术资料,其中系统地阐述了测控电路的基础理论、系统构造、核心特性及其实际应用领域。 以下是对该文献的深入解读和系统梳理:1.1测控电路在测控系统中的核心功能测控电路在测控系统的整体架构中扮演着不可或缺的角色。 它承担着对传感器输出信号进行放大、滤除杂音、提取有效信息等关键任务,并且依据测量与控制的需求,执行必要的计算、处理与变换操作,最终输出能够驱动执行机构运作的指令信号。 测控电路作为测控系统中最具可塑性的部分,具备易于放大信号、转换模式、传输数据以及适应多样化应用场景的优势。 1.2决定测控电路精确度的关键要素影响测控电路精确度的核心要素包括:(1)噪声与干扰的存在;(2)失调现象与漂移效应,尤其是温度引起的漂移;(3)线性表现与保真度水平;(4)输入输出阻抗的特性影响。 在这些要素中,噪声干扰与失调漂移(含温度效应)是最为关键的因素,需要给予高度关注。 1.3测控电路的适应性表现测控电路在测控系统中展现出高度的适应性,具体表现在:* 具备选择特定信号、灵活实施各类转换以及进行信号处理与运算的能力* 实现模数转换与数模转换功能* 在直流与交流、电压与电流信号之间进行灵活转换* 在幅值、相位、频率与脉宽信号等不同参数间进行转换* 实现量程调整功能* 对信号实施多样化的处理与运算,如计算平均值、差值、峰值、绝对值,进行求导数、积分运算等,以及实现非线性环节的线性化处理、逻辑判断等操作1.4测量电路输入信号类型对电路结构设计的影响测量电路的输入信号类型对其电路结构设计产生显著影响。 依据传感器的类型差异,输入信号的形态也呈现多样性。 主要可分为...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值