请求网络之HttpUrlConnection

本文介绍了一个使用Java的HTTPURLConnection类进行网络数据获取的例子。通过GET请求从指定URL获取JSON数据,并解析成对象显示数据大小及内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.example.day_04_httpurlconnection__;

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;
import java.net.URLConnection;
import java.util.List;

import com.example.day_04_httpurlconnection__.bean.CityInfo;
import com.example.day_04_httpurlconnection__.bean.JsonData;
import com.google.gson.Gson;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

 
 
 Handler handler=new Handler(){
  
  public void handleMessage(android.os.Message msg) {
   
   JsonData jsonData= (JsonData) msg.obj;
   
   List<CityInfo> datas=jsonData.data; 
   
   Log.i("http_", datas.size()+"");
   
   for(int i=0;i<datas.size();i++){
    
    CityInfo cityInfo = datas.get(i);
    
    cityInfo.toString();
   }
   
   
   Log.i("http_", jsonData.toString());
  };
  
 };
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // android4.0以后,在主线程做联网操作是会报错,所以要开启新线程
  // Caused by: android.os.NetworkOnMainThreadException
  new Thread() {

   public void run() {
    // 在子线程请求网络数据
    getInfo();

   };

  }.start();

 }

 /**
  * 联网请求数据
  */
 private void getInfo() {
 // String get_path = "http://www.baidu.com";
  String get_path = "http://169.254.214.171:8080/city.json";

  try {
   // 得到URL对象,设置要访问的路径
   URL url = new URL(get_path);
   // 得到联网操作类,HttpURLConnection
   HttpURLConnection openConnection = (HttpURLConnection) url
     .openConnection();
   // 设置连接超时,以毫秒为单位
   openConnection.setConnectTimeout(5000);
   // 设置请求方式,有GET和POST
   openConnection.setRequestMethod("GET");
   // 设置读取超时,以毫秒为单位
   openConnection.setReadTimeout(5000);
   // 开始连接
   openConnection.connect();
   
   
             //通过响应码判断是否连接成功
   if (openConnection.getResponseCode() == 200) {
    // 得到服务器返回的数据,是以流的形式返回的
    InputStream inputStream = openConnection.getInputStream();

    BufferedReader bufferedReader = new BufferedReader(
      new InputStreamReader(inputStream));
    // 接受流里面的数据
    String readData;
    // 拼接流里的数据,保证数据是完整的
    StringBuilder builder = new StringBuilder();
    // 使用while循环,读取流里的数据,当流里的数据被读取完毕的时候跳出循环

    while ((readData = bufferedReader.readLine()) != null) {
     builder.append(readData);
    }
    String stringData = builder.toString();

    //在数据存储时得到json的方法
    //InputStream open = getAssets().open("city.json");
    //Gson gson=new Gson();
    //gson.fromJson(new InputStreamReader(open), JsonData.class);
    
    
    Gson gson=new Gson();
    
    JsonData fromJson = gson.fromJson(stringData, JsonData.class);
    
    
   
    
    //由于android子线程不能更新UI,所以要发送数据到主线程处理
    Message message = Message.obtain();
    
    message.obj=fromJson;
    
    handler.sendMessage(message);
    
    
    
    /*runOnUiThread(new Runnable() {
     
     @Override
     public void run() {
      // TODO Auto-generated method stub
      
     }
    });*/
    
   
   }

  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值