一个简单的Demo,从聚合数据申请手机号码归属地数据接口;
在EditText中输入待查询号码,获取号码后在子线程中使用HttpUrlconnection获取JSON数据,之后进行解析;
认识Http协议
Android中发送http网络请求是很常见的,要有GET请求和POST请求。一个完整的http请求需要经历两个过程:客户端发送请求到服务器,然后服务器将结果返回给客户端,如下图所示:
-
客户端->服务器
客户端向服务器发送请求主要包含以下信息:请求的Url地址、请求头以及可选的请求体,打开百度首页,客户端向服务器发送的信息如
每个 HttpURLConnection 实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络。请求后在 HttpURLConnection 的 InputStream 或 OutputStream 上调用 close() 方法可以释放与此实例关联的网络资源,但对共享的
持久连接没有任何影响。如果在调用 disconnect() 时持久连接空闲,则可能关闭基础
套接字。
package com.bawei.demo1; 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.ProtocolException; import java.net.URL; import java.net.URLConnection; import org.apache.http.protocol.HTTP; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { private EditText editText; private TextView tv; private Handler myHandler = new Handler() { public void handleMessage(Message msg) { int arg1 = msg.what; if (arg1 == 0) { tv.setText(msg.obj.toString()); } } ; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText) findViewById(R.id.edit_text); tv = (TextView) findViewById(R.id.textView1); editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String string = s.toString(); if (s.length() == 11) { //查询 serchPhone(string); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); } private void serchPhone(final String s) { new Thread() { public void run() { String path = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=" + s; try { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 提交模式 connection.setRequestMethod("GET"); //读取超时 单位毫秒 connection.setReadTimeout(5000); //连接超时 单位毫秒 connection.setConnectTimeout(5000); //获取 int responseCode = connection.getResponseCode(); if (responseCode == 200) { InputStream inputStream = connection.getInputStream(); String string = streamToString(inputStream, "gbk"); String json = string.substring(string.indexOf("{")); Message message = Message.obtain(); message.what = 0; message.obj = json; myHandler.sendMessage(message); Log.d("string", json); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ; }.start(); } private String streamToString(InputStream inputStream, String charset) { try { //输入流 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset); //得到缓冲流 BufferedReader reader = new BufferedReader(inputStreamReader); String s = null; StringBuilder builder = new StringBuilder(); while ((s = reader.readLine()) != null) { builder.append(s); } reader.close(); return builder.toString(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" > <EditText android:id="@+id/edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/edit_text" android:layout_centerHorizontal="true" android:layout_marginTop="130dp" android:text="TextView" /> </RelativeLayout>