Android开发笔记—Http通信的基础使用
来源:互联网 发布:成绩管理系统c程序软件 编辑:程序博客网 时间:2024/05/22 16:54
为了获得联网权限,首先要在Manifest文件中注册INTERNET组件
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
new一个线程,Http通信都将在子线程中完成。
在线程中new 一个URL类,构造参数传入url地址
String strUrl = "http://wthrcdn.etouch.cn/weather_mini?city=%E9%95%BF%E6%B2%99";//地址为一个天气API的接口,发送城市名字,返回json数据。 URL url = new URL(strUrl);
然后通过url对象打开一个连接
url.openConnection();
返回一个URLConnection对象,在Android中使用HttpURLConnection
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
再使用HttpURLConnection 对象打开一个字节输入流
InputStream is = httpURLConnection.getInputStream();
将字节输入流通过new InputStreamReader的方式转换成字符流并缓存BufferedReader类里
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
循环从BufferedReader类中读出数据
String str_line = "";String result = "";while ((str_line = bufferedReader.readLine()) != null){ result += str_line;}
自此已经完成了从互联网读取数据的步骤,并已经将数据存储到String变量result中,下面通过Handler类将数据从子线程传回主线程。
先在主线程中创建一个Handler类,并重写handleMessage方法
Handler myHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); }}
然后回到子线程,将数据通过myHandler传给主线程
先创建一个Bundle对象,存储result数据
Bundle b = new Bundle();b.putString("sk_info", result);
创建一个Message对象,将Bundle对象存储,最后使用myHandler中的sendMessage()发送消息
Message msg = new Message();msg.setData(b);myHandler.sendMessage(msg);
当sendMessage后,主线程中重写的handleMessage方法就会接收到
同样的创建一个Bundle对象接收
Bundle b = msg.getData();String result = b.getString("sk_info");
自此就已经完成了子线程Http通信并且传值给主线程。
完整代码是一个读取天气的小程序:
xml布局文件
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" 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="com.example.jialin.httptest.MainActivity"> <EditText android:id="@+id/edit_city" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入城市名称,如:长沙" /> <Button android:id="@+id/btn_query" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/edit_city" android:text="查询" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Hello World!" android:layout_below="@id/btn_query" /></RelativeLayout>
Java文件:
package com.example.jialin.httptest;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import org.json.JSONException;import org.json.JSONObject;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder;public class MainActivity extends AppCompatActivity { public Handler myHandler; private Button btn_query; private EditText edit_city; private TextView textView; private String strUrl; private JSONObject jsonObject; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView1); btn_query = (Button) findViewById(R.id.btn_query); edit_city = (EditText) findViewById(R.id.edit_city); btn_query.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String str_city = edit_city.getText().toString(); if(str_city.length() < 1){ Toast.makeText(MainActivity.this, "请输入城市!", Toast.LENGTH_SHORT).show(); return ; } //开始获取API信息 try { strUrl = "http://wthrcdn.etouch.cn/weather_mini?city=" + URLEncoder.encode (str_city,"UTF-8"); new Thread(new Runnable() { @Override public void run() { try { URL url = new URL(strUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); InputStream is = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); String str_line = ""; String result = ""; while ((str_line = bufferedReader.readLine()) != null){ result += str_line; } Bundle b = new Bundle(); b.putString("sk_info", result); Message msg = new Message(); msg.setData(b); myHandler.sendMessage(msg); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }); myHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle b = msg.getData(); String getResult = b.getString("sk_info"); try { jsonObject = new JSONObject(getResult).getJSONObject("data"); String s = "当前城市:" + jsonObject.getString("city"); s += "\n当前气温:" + jsonObject.getString("wendu"); s += "\n友情提示:" + jsonObject.getString("ganmao"); textView.setText(s); } catch (JSONException e) { e.printStackTrace(); } } }; }}
示例下载 - GitHub
0 0
- Android开发笔记—Http通信的基础使用
- Android开发笔记(六十三)HTTP访问的通信方式
- [Android开发] Android客户端使用HTTP通信
- Android HTTP通信基础
- Android开发笔记—ViewPager的基础使用
- Android开发笔记—ListView的基础使用
- Android开发笔记—GridView的基础使用
- Android开发笔记—Spinner的基础使用
- Android开发笔记—WebView、ProgressDialog的基础使用
- Android学习笔记——Http通信
- Android 基础:http网络通信
- Android 开发系列:Http 通信
- android Http通信开发详解
- Android学习笔记-基于HTTP的通信技术
- 【移动开发】Android之基于HTTP协议的通信详解
- Android之Http通信——5.开发中遇到的一些问题
- 从零开发一个完整的Android项目(二)——HTTP通信
- android使用Http的Post方式与网络交互通信
- Log4j入门详解
- Android低阶 【chapter-7】GirdView和ListView常用的东西
- python enumerate() 使用
- LeetCode #315 Count of Smaller Numbers After Self
- Matlab读取带有地理信息的图像
- Android开发笔记—Http通信的基础使用
- c#中XmlTextReader读取xml
- python 安装配置、代码打包发布记录
- Hackerrank Coprime Power Sum
- 康托展开及其逆运算 详解
- Unity&Shader基础篇-“Hello Cg”
- 开始学习swift啦。第一天-01
- jsp、freemarker、json多视图混合解析
- ztree 模拟onclick事件的代码