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