Http编程之HttpURLConnection

HttpURLConnection是继承于URLConnection类,二者都是抽象类。其对象主要通过URL的openConnection方法获得的。     

下面是具体的代码:

import java.io.BufferedReader;  

import java.io.InputStreamReader;  

import java.net.HttpURLConnection;  

import java.net.URL;  

 

import android.app.Activity;  

import android.os.Bundle;  

 

public class URLConnectionActivity extends Activity {  

    String urlStr = "http://developer.android.com/";  

    /** Called when the activity is first created. */ 

    @Override 

    public void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.main);  

          

        try {  

            //实例化URL  

            URL url = new URL(urlStr);  

            //使用HttpURLConnection打开连接    

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

            //得到输入流对象  

            InputStreamReader in = new InputStreamReader(httpConnection.getInputStream());  

            BufferedReader bufReader = new BufferedReader(in);   

            String lineStr = "";  

            String resultStr = "";  

            while ((lineStr = bufReader.readLine())!=null) {  

                resultStr += lineStr + "\n";                  

            }  

              

            System.out.println(resultStr);  

            //关闭输入流  

            in.close();  

            //关闭连接   

            httpConnection.disconnect();  

        } catch (Exception e) {  

            // TODO Auto-generated catch block  

            e.printStackTrace();  

        }   

    }  


记得加上Internet权限:

 

<uses-permission android:name="android.permission.INTERNET"/>  

不然就会有UnKnownHostException.

 

默认的,不给urlConnection添加任何属性的话是使用Get方法,如果用Post可以:

urlConnection.setDoOutput(true);  

urlConnection.setRequestMethod("POST");  

 

当然还可以用setRequestProperty方法给请求添加:HostContent-TypeContent-LenthAuthentication等参数

再使用Post的时候还有一个注意点在官方文档中提及的:上传数据到服务器时为了达到最好的性能,你可以在知道数据固定大小长度的情况下使用 setFixedLengthStreamingMode(int) 方法,或者在不知道长度的情况下使用setChunkedStreamingMode(int)。因为如果不这样的话,HttpURLConnection 在发生请求之前是将数据全部放到内存里面的,这样浪费内存(会造成OutOfMemoryError)而且延时。这个东西再这里详细说了:http://www.mzone.cc/article/198.html

 

附带一个Post xml的例子:

[java] view plaincopy

HttpURLConnection urlConnection = null;  

try {  

    urlConnection = (HttpURLConnection) new URL(url).openConnection();  

    urlConnection.setDoInput(true);  

    urlConnection.setDoOutput(true);  

    urlConnection.setChunkedStreamingMode(0);  

    urlConnection.setRequestMethod("POST");  

    urlConnection.setRequestProperty("Content-Type", ("application/xml; charset=utf-8").replaceAll("\\s", ""));  

    urlConnection.setRequestProperty("Content-Length", String.valueOf(Xml.getBytes().length));  

    OutputStream out = urlConnection.getOutputStream();  

    out.write(Xml.getBytes());  

    out.close();  

    int responseCode = urlConnection.getResponseCode();  

    InputStream in = null;  

    if (responseCode == 200) {  

        in = new BufferedInputStream(urlConnection.getInputStream());  

    } else {  

        in = new BufferedInputStream(urlConnection.getErrorStream());  

    }  

    String result = readInStream(in);  

    handleResult(result);  

} catch (MalformedURLException e) {  

    e.printStackTrace();  

} catch (IOException e) {  

    e.printStackTrace();  

} finally {  

    urlConnection.disconnect();  

}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值