Android的网络通信机制


HttpClient接口

在Android6.0中,HttpClient库已经被移除

Android SDK附带的Apache的HttpClient,使用步骤如下:

  1. 使用DefaultHttpClient类实例化HttpClient对象;
  2. 创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象;
  3. 调用execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象;
  4. 通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。
HttpGet示例代码如下:
public void sendGetRequest(String Url) throws Exception {
    //创建HttpClient对象,设置默认参数
    HttpClient mHttpClient = new DefaultHttpClient();
    //创建HttpGet对象
    HttpGet mHttpGet = new HttpGet(Url);
    //添加Header
    mHttpGet.addHeader("Connection", "Keep-Alive");
    //执行Http请求
    HttpResponse mResponse = new mHttpClient.execute(mHttpGet );
    HttpEntity mHttpEntity = new mResponse().getEntity();
    if (mHttpEntity != null) {
        InputStream mInputStream = mHttpEntity.getContent();
        BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream));
        StringBuilder mStringBuilder = new StringBuilder();
        String line = null;
        try{
             while((line = mBufferedReader.readLine()) != null ) {
                 mStringBuilder.append(line );
             }
        } catch (IOException e) {
              e.printStackTrace();
        } finally {
            mInputStream.close();
      }
      Log.e("","###请求结果:" + mStringBuilder.toString());
    }
}
HttpPost示例代码如下:
public void sendPostRequest(String Url) throws Exception {
    //创建HttpClient对象,设置默认参数
    HttpClient mHttpClient = new DefaultHttpClient();
    //创建HttpGet对象
    HttpGet mHttpPost = new HttpPost(Url);
    //添加Header
    mHttpGet.addHeader("Connection", "Keep-Alive");
    //使用NameValuePair>来保存要传递的Post参数
    List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    //添加要传递的参数,BasicNameValuePair是存储键值对的类
    postParameters.add(new BasicNameValuePair("username", "myname"));
    postParameters.add(new BasicNameValuePair("password", "mypwd"));
    //实例化UrlEndecodedFormEntity对象
    UrlEncodedFormEntity mUrlEncodedFormEntity = new UrlEncodedFormEntity(postParameters);
     //使用HttpPost对象来设置UrlEncodedFormEntity的Entity
     mHttpPost.setEntity(mUrlEncodedFormEntity );
    //执行Http请求
    HttpResponse mResponse = new mHttpClient.execute(mHttpPost );
    HttpEntity mHttpEntity = new mResponse().getEntity();
    if (mHttpEntity != null) {
        InputStream mInputStream = mHttpEntity.getContent();
        BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream));
        StringBuilder mStringBuilder = new StringBuilder();
        String line = null;
        try{
             while((line = mBufferedReader.readLine()) != null ) {
                 mStringBuilder.append(line );
             }
        } catch (IOException e) {
              e.printStackTrace();
        } finally {
            mInputStream.close();
      }
      Log.e("","###请求结果:" + mStringBuilder.toString());
    }
}

HttpURLConnection接口---Google官方推荐

HttpURLConnection的压缩和缓存机制可以有效地减少网络访问的流量,提升速度和省电。

HttpURLConnection默认使用Get请求:
public void sendRequest(String url) throws IOException {
    String line = null;.
    String result = null;
    //使用HttpURLConnection 打开链接
    try{
        Url mUrl = new Url(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection ) mUrl.openConnection();
        //读取响应的内容(流)
        InputStreamReader mInputStreamReader = new InputStreamReader(new InputStream(mHttpURLConnection.getInputStream()));
        BufferedReader mBufferedReader = new BufferedReader(mInputStreamReader );
        if ((line = mBufferedReader.readLine())) {
            result = line + “\n”;
        }
        Log.e("", "请求结果:" + result);
     } catch ((MalformedURLException e)    
        {    
            Log.e(DEBUG_TAG, "MalformedURLException");    
        } finally {
        mInputStreamReader.close();
        mHttpURLConnection.disconnect();
     }

} 
HttpURLConnection的Post请求
public void sendRequest(String url) throws IOException {
    String line = null;.
    String result = null;
      try{
        Url mUrl = new Url(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection ) mUrl.openConnection();
        //设置读取超时为10秒
        mHttpURLConnection.setReadTimeout(10000);
        //设置链接超时为15秒
        mHttpURLConnection.setConnectionTimeout(15000);
        //设置请求方式
        mHttpURLConnection.setRequestMethod("Post");
        //接收输入流
        mHttpURLConnection.setDoInput(true);
        //启动输出流,当需要传递参数时需要开启
        mHttpURLConnection.setDoOutput(true);
        //添加Header
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        //添加请求参数
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        paramsList .add(new BasicNameValuePair("username", "myname"));
        paramsList .add(new BasicNameValuePair("password", "mypwd"));
        //将参数写入到输出流
        wriParams(mHttpURLConnection.getOutputStream(), paramsList);
        
        //发起请求
        mHttpURLConnection.connect();
        BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mHttpURLConnection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        while((line = mBufferedReader.readLine()) != null) {
            sb.append(line + "\n");
        }
        result = sb.toString();
         } catch ((MalformedURLException e)    
        {    
            Log.e(DEBUG_TAG, "MalformedURLException");    
        } finally {
        mHttpURLConnection.disconnect();
     }

}

private void writeParams(OutputStream mOutputStream, List<NameValuePair> paramsList){
      StringBuilder paramStr = new StringBuilder();
      for (NameValuePair pair : paramsList) {
          if (!TextUtils.isEmpty(paramStr)) {
              paramStr.append("&"):
          }
          paramStr.append(URLEncoder.encode(pair.getName(), "UTF-8"));
          paramStr.append("=");
          paramStr.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
      }
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mOutputStream, "UTF-8"));
      //将参数写入输出流
      writer.write(paramStr.toString());
      writer.flush();
      writer.close();
}

注:任何输出流都是有缓冲区的,Bufferedxxx这种输出流提供可配置缓冲区大小,其他输出流都是有默认大小的缓冲区的,FileWriter的flush()方法是从OutputStreamWriter中继承来的,其作用就是 清空缓冲区并完成文件写入操作的

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • 一、WebView view=(WebView) findViewById(R.id.webView1); vie...
    在你左右2018阅读 489评论 0 0
  • 前言 多年以前自学Java,在本地做了一些笔记。最近几年流行播客,一方面防止丢失,一方面可以帮助其他小伙伴...
    chaohx阅读 960评论 0 3
  • 使用Http通信主要有get与post两种方式,本文分别介绍使用Http的Get与Post方式与服务器通信;使用H...
    baolvlv阅读 666评论 0 0
  • 我不是诗人,所以冒出一个问题,诗人坚持下去的理由是什么? 清风告诉我,是情怀, 诗人用情怀感受生活, 哪怕一盏心灯...
    A幸运点阅读 355评论 31 7
  • 谁说太阳只是在西边呈现余晖的柔波,我可以形容那是晚霞,那是散在天边的金黄,土地的裂隙开出一株株绿色,野性的花朵开放...
    二马行空阅读 521评论 2 7