Android HTTP

Android请求网络行为需要声明权限;

<!-- 访问Internet权限-->



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

 

Http请求头;
 Request-Line----GET/HTTP/1.1 代表以get方式请求1.1版本的HTTP协议。
 Accept ---------*/* 代表浏览器可以接受所有的数据类型。
 Accept-Encoding-gzip, deflate代表浏览器可以接收压缩过后的数据。当服务器给客户端传输数据的时候为了减少流量,可以进行压缩,压缩之后的数据传给浏览器,浏览器可以进行自动解压缩。
 Accpet-Language---zh-cn代表客户端浏览器的语言。
 Connection----Keep-Alive代表维护长度链接。
 Cookie-----YYID=612341421241241124* 代表cookid的值
 Host----www.sohu.com 代表请求的主机名。
 If-Modified-since----Sat,27 Mar 2010 02:09:14 GMT;length=250408代表网页内容的访问的时间。
 User-Agent----Mozilla/4.0(compatible;MSIE 6.0;windows NT 5.1;SV1;CIBA) d代表IE浏览器作为软件的标识。
 
 服务器返回给客户端的内容:
  HTML
  XML
  JSON

 

 1 public class MyHttp {

 2     private static InputStream  inStream = null;

 3     public void main()

 4     {

 5         HttpUrl("http://www.baidu.com/img/bdlogo.gif");

 6     }

 7     public static Bitmap HttpUrl(String path)

 8     {

 9         try {

10             URL url = new URL(path);

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

12             conn.setConnectTimeout(5000);//设置超时

13             conn.setRequestMethod("GET"); //设置请求方法。

14             //获得请求状态吗

15             if(conn.getResponseCode()==200)

16             {

17                 //获得输入流

18                 inStream = conn.getInputStream();

19                 //编码流   decode 编码 Stream

20                 Bitmap bitmap = BitmapFactory.decodeStream(inStream);

21                 

22                 return bitmap;

23             }

24         } catch (MalformedURLException e) {

25             

26         } catch (IOException e) {

27             e.printStackTrace();

28         }finally{

29             try {

30                 if(inStream!=null){

31                     inStream.close();                    

32                 }

33             } catch (IOException e) {

34                 e.printStackTrace();

35             }

36         }

37         return null;

38     }

39 }
URLConnection

1:创建URL 实例。

2::HttpURLConnection conn = (HttpURLConnection)url.openCOnnection();相当于打开链接;

3:设置超时请求,设置请求方式等。 setConnectTimeout(5000);,setRequestMethod("GET");  POST

4:判断返回结果码 conn.getResponseCode()==200为正常。

5:开始处理 获取流:conn.getInputStream();

 


  

 

 

 

 

你可能感兴趣的:(android)