你的位置:首页 > 操作系统

[操作系统]Android自学历程—HttpURLConnection的简单使用


前段时间学习了OkHttp,可对于她的理解还不够。恰好又听说HttpURLConnection在逐渐的向OkHttp靠拢,于是决定玩玩HttpURLConnection,恰好网上关于这部分的知识相对比较的多,Demo也好找。前人栽树,后人乘凉,表示敬意。借鉴别人的,是学习路上不可缺少的一步。恩对,所以本文参考借鉴自:http://blog.csdn.net/yanzi1225627/article/details/22222735

http://lzyblog.com/2014/09/18/HttpClient%E5%92%8CHttpURLConnection%E7%9A%84%E4%BD%BF%E7%94%A8%E5%92%8C%E5%8C%BA%E5%88%AB-%E4%B8%8B/

 

当然,还会有来自新手的个人笔记。这部分的知识也不是孤立的,除了HttpURLConnection的使用,还有离不开的线程和如何更新主UI的问题。最后大神给建议,新手来学习。

 

一如既往,先看图片。

 

 布局看似简单,但这里我们我们用到了 FrameLayout的布局方式(组建叠加的效果),虽然不怎么常见,但Fragment一定是大家以后学习会遇到的知识点。

<RelativeLayout ="http://schemas.android.com/apk/res/android"  ="http://schemas.android.com/tools"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:paddingBottom="@dimen/activity_vertical_margin"  android:paddingLeft="@dimen/activity_horizontal_margin"  android:paddingRight="@dimen/activity_horizontal_margin"  android:paddingTop="@dimen/activity_vertical_margin"  tools:context=".MainActivity">  <FrameLayout    android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView      android:id="@+id/textView"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:text="Show_message"/>    <ImageView      android:id="@+id/imageView"      android:layout_width="wrap_content"      android:layout_height="match_parent"      android:layout_gravity="center"/>  </FrameLayout>  <Button    android:id="@+id/button01"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_alignParentBottom="true"    android:layout_alignParentLeft="true"    android:text="访问百度"/>  <Button    android:id="@+id/button02"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_alignParentBottom="true"    android:layout_alignParentRight="true"    android:text="下载图片"/></RelativeLayout>

 

下面的才是主要的逻辑代码:实现的功能是,通过HttpUrlConnect获取网页信息和下载图片。

package com.ryan.httpurlconnectiondemo01;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.AsyncTask;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * 本实例参考:http://blog.csdn.net/yanzi1225627/article/details/22222735 * */public class MainActivity extends AppCompatActivity implements View.OnClickListener{  private TextView textView;  private ImageView imageView;  private Button webButton;  private Button imgButton;  String resultStr = ""; //getURLResponse()方法返回的值  private void initView() {    textView = (TextView) findViewById(R.id.textView);    imageView = (ImageView) findViewById(R.id.imageView);    webButton = (Button) findViewById(R.id.button01);    imgButton = (Button) findViewById(R.id.button02);    webButton.setOnClickListener(this);    imgButton.setOnClickListener(this);  }  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    initView();  }  @Override  public void onClick(View v) {    switch (v.getId()){      case R.id.button01:        // TODO: 15-9-10 获取网页信息        textView.setVisibility(View.VISIBLE);        imageView.setVisibility(View.GONE);        //开启线程        Thread visitWebThread = new Thread(new visitWebRunnable());        visitWebThread.start();        try {          //等待多线程里的子线程结束再执行          visitWebThread.join();          if (!resultStr.equals("")){            textView.setText(resultStr);          }        } catch (InterruptedException e) {          e.printStackTrace();        }        break;      case R.id.button02:        // TODO: 15-9-10 获取网络图片        textView.setVisibility(View.GONE);        imageView.setVisibility(View.VISIBLE);        String imgUrl = "http://pic.cnblogs.com/avatar/790633/20150727124352.png";        //AsyncTask()        new DownImgAsyncTask().execute(imgUrl);        break;    }  }  private class visitWebRunnable implements Runnable {    @Override    public void run() {      String date = getURlResponse("http://www.baidu.com/");      resultStr = date;    }  }  private String getURlResponse(String s) {    HttpURLConnection httpURLConnection = null;    InputStream inputStream = null;    String resultData ="";    try {      URL url = new URL(s);  //URl对象      httpURLConnection = (HttpURLConnection) url.openConnection();  //使用URl打开一个链接        httpURLConnection.setDoInput(true);//允许输入流,即允许下载        httpURLConnection.setDoOutput(true);//允许输出流,即允许上传        httpURLConnection.setUseCaches(false); //不使用缓冲        httpURLConnection.setRequestMethod("GET"); //使用get请求      inputStream = httpURLConnection.getInputStream();//获取输入流,此时才真正建立链接      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));      String inputLine;      while ((inputLine = bufferedReader.readLine())!= null){        resultData = inputLine + resultData + "\n";      }    } catch (MalformedURLException e) {      e.printStackTrace();    } catch (IOException e) {      e.printStackTrace();    }finally {      try {        inputStream.close();      } catch (IOException e) {        e.printStackTrace();      }      httpURLConnection.disconnect();    }    return resultData;  }  private class DownImgAsyncTask extends AsyncTask {//    @Override//    protected void onPreExecute() {//      super.onPreExecute();//      imageView.setImageBitmap(null);//      showProgressBar();//显示进度条提示框//    }    @Override    protected Object doInBackground(Object[] params) {      Bitmap b = getImageBitmap(String.valueOf(params[0]));      return b;    }    @Override    protected void onPostExecute(Object o) {      super.onPostExecute(o);      imageView.setImageBitmap((Bitmap) o);    }  }  private Bitmap getImageBitmap(String url) {    URL imgUrl = null;    Bitmap bitmap = null;    try {      imgUrl = new URL(url);      HttpURLConnection httpURLConnection = (HttpURLConnection) imgUrl.openConnection();        httpURLConnection.setDoInput(true);        httpURLConnection.connect();      InputStream inputStream = httpURLConnection.getInputStream();      bitmap = BitmapFactory.decodeStream(inputStream);      inputStream.close();    } catch (MalformedURLException e) {      e.printStackTrace();    } catch (IOException e) {      e.printStackTrace();    }    return bitmap;  }  @Override  public boolean onCreateOptionsMenu(Menu menu) {    // Inflate the menu; this adds items to the action bar if it is present.    getMenuInflater().inflate(R.menu.menu_main, menu);    return true;  }  @Override  public boolean onOptionsItemSelected(MenuItem item) {    // Handle action bar item clicks here. The action bar will    // automatically handle clicks on the Home/Up button, so long    // as you specify a parent activity in AndroidManifest.    int id = item.getItemId();    //noinspection SimplifiableIfStatement    if (id == R.id.action_settings) {      return true;    }    return super.onOptionsItemSelected(item);  }}

 

这里我重构的代码减去了原文的showProgressBar()的方法,即现实下载进度条的现实。

获取网页信息部分:

其线程的实现方式我们之前也见过了。

Thread visitWebThread = new Thread(new visitWebRunnable());        visitWebThread.start();private class visitWebRunnable implements Runnable {    @Override    public void run() {        
        String date = getURlResponse("http://www.baidu.com/");

        resultStr = date;
} }

 

之后便是通过HpptURLConnect实现打印网页信息

  private String getURlResponse(String s) {    HttpURLConnection httpURLConnection = null;    InputStream inputStream = null;    String resultData ="";    try {      URL url = new URL(s);  //URl对象      httpURLConnection = (HttpURLConnection) url.openConnection();  //使用URl打开一个链接        httpURLConnection.setDoInput(true);//允许输入流,即允许下载        httpURLConnection.setDoOutput(true);//允许输出流,即允许上传        httpURLConnection.setUseCaches(false); //不使用缓冲        httpURLConnection.setRequestMethod("GET"); //使用get请求      inputStream = httpURLConnection.getInputStream();//获取输入流,此时才真正建立链接      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));      String inputLine;      while ((inputLine = bufferedReader.readLine())!= null){        resultData = inputLine + resultData + "\n";      }    } catch (MalformedURLException e) {      e.printStackTrace();    } catch (IOException e) {      e.printStackTrace();    }finally {      try {        inputStream.close();      } catch (IOException e) {        e.printStackTrace();      }      httpURLConnection.disconnect();    }    return resultData;  }

一.创建HttpURLConnection对象

URL url = new URL("xxxxxx"); URLConnection urlConnection = url.openConnection();HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;

二.HttpURLConnection参数设置

 

 

 

 

 

原谅我,写的太好了,我就直接截图了。

 

关于网页信息的更新

网页信息的更新上并没有使用什么方法,而是将所需的信息保存到resultStr的String类型的变量中,直接在主UI线程中进行直接的更新,当然原作者使用了Thread.join的方法,确保了信息的完整。

关于此方法原作者也表示了,

 

 

关于下载图片部分

这里与获取网页信息最主要不同点在于:线程的实现方式

 String imgUrl = "http://pic.cnblogs.com/avatar/790633/20150727124352.png";        //AsyncTask()        new DownImgAsyncTask().execute(imgUrl);

 

 

在AsyncTask里其实能实现很多的方法,这里我先粗略的了解了doInBackground,onPostExecute方法的作用。

1.params参数在贯穿的地方

2.doinbackground方法返回的值,与onPostExecute之间的联系。

 

我原本以为获取图片会很难,没想到这么有这么简单的方式:

bitmap = BitmapFactory.decodeStream(inputStream);

 

还有个重要的不要忘记添加
<uses-permission android:name="android.permission.INTERNET"></uses-permission>


到这里基本结束了,后面将会对Handler或AsyncTask的使用进一步去了解。