首页 > 代码库 > HttpURLConnection获取数据

HttpURLConnection获取数据

使用步骤:

1.创建Url

2.用Url打开连接

3.设置请求参数

4. 获取响应状态码

  2xxx 请求成功 3xxx重定向 4xxx资源错误 5xxx服务器错误

5.获取服务器返回的二进制输入流

6.添加网络权限
  <uses-permission android:name="android.permission.INTERNET"/>

 


示例代码:

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
   private EditText   etPath;
   private ImageView  iv;
   private String     path;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      etPath = (EditText) findViewById(R.id.et_path);
      // 在主线程中创建
      iv = (ImageView) findViewById(R.id.iv);
   }
   // 1. 在主线程中创建Hanlder对象
   Handler  mHandler = new Handler() {
      public void handleMessage(Message msg) {
         // 把图片显示在imageview上
         iv.setImageBitmap((Bitmap)msg.obj);
      };
   };
   // 3. 在handleMessage()中修改UI

   /**
    * 1. 获取服务器返回的二进制输入流 
    * 2. 把流转成位图对象 
    * 3. 把图片显示在imageview上
    */
   public void look(View v) {
      System.out.println("点击按钮的线程:" + Thread.currentThread().getName());
       path = etPath.getText().toString().trim();
      if (TextUtils.isEmpty(path) || !path.startsWith("http")) {
         Toast.makeText(this, "请输入正确的网址", 0).show();
         return;
      }
      // 开启线程
      new Thread() {
         public void run() {
            requestNetWork();
         };
      }.start();
   }
   /**
    * 网络通讯
    */
   protected void requestNetWork() {
      try {
         // 1. 写一个Url
         URL url = new URL(path);
         // 2. 用这个Url打开http连接
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         // 3. 设置请求参数
         // 不设置,默认就是get请求
         conn.setRequestMethod("GET");
         conn.setConnectTimeout(3000);
         // 4. 获取状态吗
         // * 2xxx响应成功 3xxx重定向 4xxx资源错误 5xxx服务器错误
         int code = conn.getResponseCode();
         if (code == 200) {
            // 5. 获取服务返回的二进制输入流
            InputStream is = conn.getInputStream();
            // 把流转成位图对象
            Bitmap bmp = BitmapFactory.decodeStream(is);
            // 2. 在子线程中用handler发消息
            Message msg = new Message();
            msg.obj = bmp;
            mHandler.sendMessage(msg);
         } else {
            // Toast.makeText(this, "code:"+code, 0).show();
       }
      } catch (Exception e) {
         e.printStackTrace();
         // Toast.makeText(this, "服务器忙", 0).show();
      }
   }
}

查看网络文字示例代码
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

   private static final int MSG_SUCC    = 0;
   private static final int MSG_ERR         = 1;
   private static final int MSG_ERR_CODE = 2;
   private EditText         etPath;
   private TextView         tvContent;
   private String           path;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      etPath = (EditText) findViewById(R.id.et_path);
      tvContent = (TextView) findViewById(R.id.tv);
   }
   /**
    *  1. 获取用户输入的网址,做非空判断
    *  2. 在子线程中进行网络通讯 
    *  3. 获取服务器返回的二进制数据流
    *  4. 把流转成文字 
    *  5. 用Handler显示文字
    */
   public void look(View v) {
      // 获取用户输入的网址,做非空判断
      path = etPath.getText().toString().trim();
      if (TextUtils.isEmpty(path) || !path.startsWith("http")) {
         Toast.makeText(this, "亲,请输入正确的网址,例如http开头", 0).show();
         return;
      }
      // 在子线程中进行网络通讯
      new Thread() {
         public void run() {
            requestNetWork();
         };
      }.start();
   }
   /**
    * 获取服务器返回的二进制数据流
    */

   protected void requestNetWork() {
      try {
         // 1. 写一个Url
         URL url = new URL(path);
         // 2. 用这个Url打开http连接
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         // 3. 设置请求参数
         conn.setRequestMethod("GET");
         conn.setConnectTimeout(3000);
         // 4. 获取状态吗
         // * 2xxx响应成功 3xxx重定向 4xxx资源错误 5xxx服务器错误
         int code = conn.getResponseCode();
         if (code == 200) {
            // 5. 获取服务返回的二进制输入流
            InputStream is = conn.getInputStream();
            // 把流转成文字
            String text = StringUtils.parseStream2Str(is);
            // 用Handler显示文字
            Message msg = Message.obtain();// 从消息池中获取消息
            msg.obj = text;
            msg.what = MSG_SUCC;
            mHandler.sendMessage(msg);
         } else {
            Message msg = Message.obtain();// 从消息池中获取消息
            msg.obj =  code;
            msg.what =MSG_ERR_CODE;
            mHandler.sendMessage(msg);

         }

      } catch (Exception e) {

         e.printStackTrace();

         mHandler.sendEmptyMessage(MSG_ERR);
      }
   }
   Handler  mHandler = new Handler() {
      public void handleMessage(Message msg) {
        switch (msg.what) {
           case MSG_SUCC:
              tvContent.setText((String) msg.obj);
                break;
            case MSG_ERR_CODE:
               Toast.makeText(MainActivity.this, "code:"+msg.obj, 0).show();
                break;
            case MSG_ERR:
                Toast.makeText(MainActivity.this, "服务器忙", 0).show();
                break;
            default:
                break;
         }
      };
   };
}

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
/**
 * 操作字符
 */
public class StringUtils {
   /**
    * 从流中转成字符串
    * 
    * @param is
    *            输入流
    * @return null表示失败
    */
   public static String parseStream2Str(InputStream is) {
      //内存输出流
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int len = -1;
      byte[] buffer = new byte[1024*8];
      try {
         while((len = is.read(buffer)) != -1){
            baos.write(buffer, 0, len);
         }
         return new String(baos.toByteArray());
      } catch (Exception e) {
         e.printStackTrace();
         return null;
      }
   }
}

 

 

HttpURLConnection获取数据