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

    转自http://blog.csdn.net/redoffice/article/details/7552137

    本文总结了一下《Android应用开发揭秘》里面关于Http通信部分HttpURLConnection接口的相关知识。

    HttpURLConnection接口

    Http通信协议中,使用的最多的就是GetPostGet请求可以获取静态页面,也可以把参数放在字串后面,传递给服务器。PostGet不同的是Post的参数不是放在URL字串的里面,而是放在http请求数据中。

    HttpURLConnectionJAVA的标准类,继承自URLConnection类;

    HttpURLConnectionURLConnection类都是抽象类,无法直接实例化对象。

    其对象主要是通过URLopenConnection方法获得。

     

    实例定义代码:

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

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

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

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

    [java] view plaincopy
    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();  

     

    利用GetPost方式来获取一个网页内容。

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

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

    [java] view plaincopy
    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方式访问服务器,以及访问服务器端图片并显示在客户端。

    代码如下:

    [java] view plaincopy
    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这个环境变量中读取,便于传送较大一些的数据,同时因为不暴露数据在浏览器的地址栏中,安全性相对较高,但这样的处理效率会受到影响。


  • 相关阅读:
    python配置apache的web服务器方法(python的CGI配置)
    【转】移动web资源整理
    CSS实现背景透明,文字不透明,兼容所有浏览器
    html5 css3 如何绘制扇形任意角度
    Chrome 将默认不播放非重要 Flash 内容
    微信video标签全屏无法退出bug
    百度bae定时任务使用方法
    判断浏览器是否支持某个css3属性的javascript方法
    javascript检测是否安装了flash
    移动前端不得不了解的html5 head 头标签
  • 原文地址:https://www.cnblogs.com/walccott/p/4957580.html
Copyright © 2011-2022 走看看