Android开发笔记—Http通信的基础使用
2016-10-18 17:11
411 查看
为了获得联网权限,首先要在Manifest文件中注册INTERNET组件
new一个线程,Http通信都将在子线程中完成。
在线程中new 一个URL类,构造参数传入url地址
然后通过url对象打开一个连接
返回一个URLConnection对象,在Android中使用HttpURLConnection
再使用HttpURLConnection 对象打开一个字节输入流
将字节输入流通过new InputStreamReader的方式转换成字符流并缓存BufferedReader类里
循环从BufferedReader类中读出数据
自此已经完成了从互联网读取数据的步骤,并已经将数据存储到String变量result中,下面通过Handler类将数据从子线程传回主线程。
先在主线程中创建一个Handler类,并重写handleMessage方法
然后回到子线程,将数据通过myHandler传给主线程
先创建一个Bundle对象,存储result数据
创建一个Message对象,将Bundle对象存储,最后使用myHandler中的sendMessage()发送消息
当sendMessage后,主线程中重写的handleMessage方法就会接收到
同样的创建一个Bundle对象接收
自此就已经完成了子线程Http通信并且传值给主线程。
完整代码是一个读取天气的小程序:
xml布局文件
Java文件:
示例下载 - GitHub
<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
相关文章推荐
- Java基础知识强化之网络编程笔记17:Android网络通信之 使用Http的Post方式读取网络数据(基于HTTP通信技术)
- Java基础知识强化之网络编程笔记16:Android网络通信之 使用Http的Get方式读取网络数据(基于HTTP通信技术)
- Java基础知识强化之网络编程笔记18:Android网络通信之 使用HttpClient的Post / Get 方式读取网络数据(基于HTTP通信技术)
- Android开发笔记(六十三)HTTP访问的通信方式
- Android开发笔记—ListView的基础使用
- Android App开发基础篇—HttpURLConnection基础使用
- Android逆向基础笔记—Android NDK开发3之使用ndk-build工具手动编译
- android开发笔记之网络编程—使用HTTP进行网络编程
- Android开发-基础网络组件(1)使用HttpURLConnection登陆-注意打开网络需要在线程中执行-主线程不支持
- Java基础知识强化之网络编程笔记15:Android网络通信之 Android异步任务处理(AsyncTask使用)
- Android核心基础-7.Android 网络通信-2.使用开源项目AsyncHttpClient
- Android开发笔记—Spinner的基础使用
- Android开发笔记—ViewPager的基础使用
- Android开发笔记—GridView的基础使用
- Android开发-基础网络组件(2)使用ApacheHttpClient登陆-AndroidStudio
- Android开发-基础网络组件(1)使用HttpURLConnection登陆-AndroidStudio
- Android开发笔记—WebView、ProgressDialog的基础使用
- HTTP基础与Android之(安卓与服务器通信)——使用HttpClient和HttpURLConnection
- Android开发笔记(一百一十)使用http框架上传文件
- 【Android笔记】Android开发之Http通信HttpURLConnection接口