zoukankan      html  css  js  c++  java
  • 【Android笔记】Android开发之Http通信HttpURLConnection接口

    HttpURLConnection接口

    Http通信协议中,使用的最多的就是Get和Post。

    Get请求可以获取静态页面,也可以把参数放在字串后面,传递给服务器。

    Post与Get不同的是Post的参数不是放在URL字串的里面,而是放在http请求数据中。

    HttpURLConnection是JAVA的标准类,继承自URLConnection类;

    HttpURLConnection和URLConnection类都是抽象类,无法直接实例化对象。

    其对象主要是通过URL的openConnection方法获得。

    实例定义代码:

    1 //构造一个URL对象
    2 url = new URL(httpUrl);
    3 //使用HttpURLConnection打开链接,urlConn就是实例对象
    4 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

    openConnection方法只是创建了一个HttpURLConnection或者URLConnection的实例,并不进行真正的链接操作。

    每次openConnection的时候都将创建一个新的实例。

    因此在连接之前可以对该对象的属性进行设置。

    1 //设置输入(输出)流
    2                 urlConn.setDoOutput(true);
    3                 urlConn.setDoInput(true);
    4                 //设置以POST方式
    5                 urlConn.setRequestMethod("POST");
    6                 //POST请求不能使用缓存
    7                 urlConn.setUseCaches(false);
    8 //在连接完成之后可以关闭这个连接
    9                 urlConn.disconnect();

    利用Get和Post方式来获取一个网页内容。

    HttpURLConnection默认使用Get方式,如果要使用Post方式,则需要setRequestMethod设置。然后将我们要传递的参数内容通过weiteBytes方法写入数据流。

    Get方式访问无参数的代码:

     1 /*
     2  *  HttpURLConnectionActivity02.java
     3  *  北京Android俱乐部群:167839253
     4  *  Created on: 2012-5-9
     5  *  Author: blueeagle
     6  *  Email: liujiaxiang@gmail.com
     7  */
     8 
     9 public class HttpURLConnectionActivity02 extends Activity {
    10     /** Called when the activity is first created. */
    11     
    12     private final String DEBUG_TAG = "HttpURLConnectionActivityActivity";
    13     @Override
    14     public void onCreate(Bundle savedInstanceState)    {
    15         super.onCreate(savedInstanceState);
    16         setContentView(R.layout.main);        
    17         TextView mTextView = (TextView)this.findViewById(R.id.myTextView);
    18         //http地址
    19         String httpUrl = "http://10.1.69.34/http1.jsp";
    20         //获得的数据
    21         String resultData = "";
    22         URL url = null;
    23         try
    24         {
    25             //构造一个URL对象
    26             url = new URL(httpUrl); 
    27         }
    28         catch (MalformedURLException e)
    29         {
    30             Log.e(DEBUG_TAG, "MalformedURLException");
    31         }
    32         if (url != null)
    33         {
    34             try
    35             {
    36                 //使用HttpURLConnection打开连接
    37                 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    38                 //得到读取的内容(流)
    39                 InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
    40                 // 为输出创建BufferedReader
    41                 BufferedReader buffer = new BufferedReader(in);
    42                 String inputLine = null;
    43                 //使用循环来读取获得的数据
    44                 while (((inputLine = buffer.readLine()) != null))
    45                 {
    46                     //我们在每一行后面加上一个"
    "来换行
    47                     resultData += inputLine + "
    ";
    48 
    49                 }    
    50                 
    51                 if ( !resultData.equals("") )
    52                 {
    53                     mTextView.setText(resultData);
    54                 }
    55                 else
    56                 {
    57                     mTextView.setText("读取的内容为NULL");
    58                 }
    59                 //关闭InputStreamReader
    60                 in.close();
    61                 //关闭http连接
    62                 urlConn.disconnect();
    63                 //设置显示取得的内容
    64 
    65             }
    66             catch (IOException e)
    67             {
    68                 Log.e(DEBUG_TAG, "IOException");
    69             }
    70         }
    71         else
    72         {
    73             Log.e(DEBUG_TAG, "Url NULL");
    74         }
    75         //设置按键事件监听
    76         Button button_Back = (Button) findViewById(R.id.Button_back);
    77         /* 监听button的事件信息 */
    78         button_Back.setOnClickListener(new Button.OnClickListener() 
    79         {
    80             public void onClick(View v)
    81             {
    82                 /* 新建一个Intent对象 */
    83                 Intent intent = new Intent();
    84                 /* 指定intent要启动的类 */
    85                 intent.setClass(HttpURLConnectionActivity02.this, HttpURLConnectionActivity.class);
    86                 /* 启动一个新的Activity */
    87                 startActivity(intent);
    88                 /* 关闭当前的Activity */
    89                 HttpURLConnectionActivity02.this.finish();
    90             }
    91         });
    92     }     
    93 }

    POST方式访问服务器,以及访问服务器端图片并显示在客户端。

    代码如下:

      1 /*
      2  *  HttpURLConnectionActivity02.java
      3  *  北京Android俱乐部群:167839253
      4  *  Created on: 2012-5-9
      5  *  Author: blueeagle
      6  *  Email: liujiaxiang@gmail.com
      7  */
      8 
      9 public class HttpURLConnectionActivity03 extends Activity {
     10     /** Called when the activity is first created. */
     11     private final String DEBUG_TAG = "Activity03";
     12     private Bitmap bmp;
     13     @Override
     14     public void onCreate(Bundle savedInstanceState)    {
     15         super.onCreate(savedInstanceState);
     16         setContentView(R.layout.main);        
     17         TextView mTextView = (TextView)this.findViewById(R.id.myTextView);
     18         ImageView mImageView = (ImageView)this.findViewById(R.id.bmp);
     19         //http地址
     20         String httpUrl = "http://10.1.69.34/http1.jsp";
     21         //获得的数据
     22         String resultData = "";
     23         URL url = null;
     24         try
     25         {
     26             //构造一个URL对象
     27             url = new URL(httpUrl); 
     28         }
     29         catch (MalformedURLException e)
     30         {
     31             Log.e(DEBUG_TAG, "MalformedURLException");
     32         }
     33         if (url != null)
     34         {
     35             try
     36             {
     37                 //使用HttpURLConnection打开链接
     38                 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
     39 //********************************Post方式不同的地方*************************************//
     40                 //因为这个是post请求,需要设置为true
     41                 urlConn.setDoOutput(true);
     42                 urlConn.setDoInput(true);
     43                 //设置以POST方式
     44                 urlConn.setRequestMethod("POST");
     45                 //POST请求不能使用缓存
     46                 urlConn.setUseCaches(false);
     47                 urlConn.setInstanceFollowRedirects(true);
     48                 
     49                 //配置本次连接的Content_type,配置为application/x-www-form-urlencoded
     50                 urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
     51                 //连接,从postUrl.OpenConnection()至此的配置必须要在connect之前完成。
     52                 //要注意的是connection.getOutputStream会隐含地进行connect.
     53 //********************************Post方式不同的地方*************************************//
     54                 urlConn.connect();
     55                 //DataOutputStream流。
     56                 DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
     57                 //要上传的参数
     58                 String content = "par=" + URLEncoder.encode("ABCDEF","gb2312");
     59                 //将要上传的内容写入流中
     60                 out.writeBytes(content);
     61                 //刷新、关闭
     62                 out.flush();
     63                 out.close();
     64                 //获取数据
     65                 BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
     66                 String inputLine = null;
     67                 
     68                 //---///得到读取的内容(流)
     69                 //---InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
     70                 //---// 为输出创建BufferedReader
     71                 //---BufferedReader buffer = new BufferedReader(in);
     72                 //---String inputLine = null;
     73                 //---//使用循环来读取获得的数据
     74                 while (((inputLine = reader.readLine()) != null))
     75                 {
     76                     //我们在每一行后面加上一个"
    "来换行
     77                     resultData += inputLine + "
    ";
     78 
     79                 }    
     80                 reader.close();
     81                 //关闭http链接
     82                 urlConn.disconnect();
     83                 //设置显示取得的内容
     84                 
     85                 if ( !resultData.equals("") )
     86                 {
     87                     mTextView.setText(resultData);
     88                     bmp = this.GetNetBitmap("http://10.1.69.34/0.jpg");
     89                     mImageView.setImageBitmap(bmp);
     90                 }
     91                 else
     92                 {
     93                     mTextView.setText("读取的内容为空");
     94                 }
     95                 //关闭InputStreamReader
     96                 reader.close();
     97                 //关闭http连接
     98                 urlConn.disconnect();
     99                 //设置显示取得的内容
    100 
    101             }
    102             catch (IOException e)
    103             {
    104                 Log.e(DEBUG_TAG, "IOException");
    105             }
    106         }
    107         else
    108         {
    109             Log.e(DEBUG_TAG, "Url NULL");
    110         }
    111         //设置按键事件监听
    112         Button button_Back = (Button) findViewById(R.id.Button_back);
    113         /* 监听button的事件信息 */
    114         button_Back.setOnClickListener(new Button.OnClickListener() 
    115         {
    116             public void onClick(View v)
    117             {
    118                 /* 新建一个Intent对象 */
    119                 Intent intent = new Intent();
    120                 /* 指定intent要启动的类 */
    121                 intent.setClass(HttpURLConnectionActivity03.this, HttpURLConnectionActivity.class);
    122                 /* 启动一个新的Activity */
    123                 startActivity(intent);
    124                 /* 关闭当前的Activity */
    125                 HttpURLConnectionActivity03.this.finish();
    126             }
    127         });
    128     }
    129   //********************************获取网络图片(支持bmp,jpg,png,gif等格式,但是bmp格式支持的比较小)*************************************//    
    130     public Bitmap GetNetBitmap(String url){
    131         URL imageUrl = null;
    132         Bitmap bitmap = null;
    133         try{
    134             imageUrl = new URL(url);
    135         }
    136         catch(MalformedURLException e){
    137             Log.e(DEBUG_TAG, e.getMessage());
    138         }
    139         try{
    140             HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
    141             conn.setDoInput(true);
    142             conn.connect();
    143             //将得到的数据转换成InputStream
    144             InputStream is = conn.getInputStream();
    145             //将InputStream 转换成Bitmap
    146             bitmap = BitmapFactory.decodeStream(is);
    147             is.close();
    148         }
    149         catch(IOException e){
    150             Log.e(DEBUG_TAG, e.getMessage());
    151         }
    152         return bitmap;
    153         
    154     }
    155 }

    总结:

    针对HTTP协议,简单来说:

    GET方式是通过把参数键值对附加在url后面来传递的,是文本方式的。

    在服务器端可以从'QUERY_STRING'这个变量中直接读取,效率较高,但缺乏安全性,也无法来处理复杂的数据,长度有限制。主要用于传递简单的参数。

    POST方式:就传输方式讲参数会被打包在http报头中传输,可以是二进制的。
    从CONTENT_LENGTH这个环境变量中读取,便于传送较大一些的数据,同时因为不暴露数据在浏览器的地址栏中,安全性相对较高,但这样的处理效率会受到影响。

    参考原文:http://blog.csdn.net/redoffice/article/details/7552137

  • 相关阅读:
    h5唤起app
    app唤起的完美解决方案,及阻止浏览器的默认弹窗行为
    cdn
    函数声明和函数表达式的区别
    基础系列(7)—— 结构
    基础系列(4)—— C#装箱和拆箱
    重温软件工程——对软件工程的初步了解
    基础系列(9)—— 抽象方法和接口
    自学系列--git的基础简介
    设计模式之简单工厂模式
  • 原文地址:https://www.cnblogs.com/tanghuian/p/4081951.html
Copyright © 2011-2022 走看看