zoukankan      html  css  js  c++  java
  • Android HttpURLConnection

    1.HttpURLConnection连接URL

    1)创建一个URL对象

    URL url = new URL(http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101190101);

    2)利用HttpURLConnection对象从网络中获取网页数据

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

    3)设置连接超时

    conn.setConnectTimeout(5000);

    4)对响应码进行判断

    if (conn.getResponseCode() != 200)    //从Internet获取网页,发送请求,将网页以流的形式读回来

    throw new RuntimeException("请求url失败");

    5)得到网络返回的输入流

    InputStream is = conn.getInputStream();

    6)String result = readData(is, "UTF-8"); //文件流输入出文件用outStream.write

    7)conn.disconnect();

    总结:

    --记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操作.

    --返回的响应码200,是成功.

    --在Android中对文件流的操作和JAVA SE上面是一样的.

    --在对大文件的操作时,要将文件写到SDCard上面,不要直接写到手机内存上.

    --操作大文件是,要一遍从网络上读,一遍要往SDCard上面写,减少手机内存的使用.这点很重要,面试经常会被问到.

    --对文件流操作完,要记得及时关闭.

    2.向Internet发送请求参数

    步骤:

    1)创建URL对象:URL realUrl = new URL(requestUrl);

    2)通过HttpURLConnection对象,向网络地址发送请求

    HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();

    3)设置容许输出:conn.setDoOutput(true);

    4)设置不使用缓存:conn.setUseCaches(false);

    5)设置使用POST的方式发送:conn.setRequestMethod("POST");

    6)设置维持长连接:conn.setRequestProperty("Connection", "Keep-Alive");

    7)设置文件字符集:conn.setRequestProperty("Charset", "UTF-8");

    8)设置文件长度:conn.setRequestProperty("Content-Length", String.valueOf(data.length));

    9)设置文件类型:conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

    10)以流的方式输出.

    总结:

    --发送POST请求必须设置允许输出

    --不要使用缓存,容易出现问题.

    --在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成HTML文件头.

     
     
  • 相关阅读:
    List of the best open source software applications
    Owin对Asp.net Web的扩展
    NSwag给api加上说明
    'workspace' in VS Code
    unable to find valid certification path to requested target
    JMeter的下载以及安装使用
    exception disappear when forgot to await an async method
    Filter execute order in asp.net web api
    记录web api的request以及response(即写log)
    asp.net web api的源码
  • 原文地址:https://www.cnblogs.com/chenly-index/p/4195722.html
Copyright © 2011-2022 走看看