您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
45_调用webservice获取电话号码归属地
发布时间:2021-02-26 16:18:09编辑:雪饮阅读()
webservice接口
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edit_mobile"
android:hint="@string/placeholder"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/location_button"
android:id="@+id/location_button"
/>
</RelativeLayout>
</LinearLayout>
布局文件中的相关值strings.xml:
将上面获取的appcode单独放在一个配置文件中会比较好点,建立values/config.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.queryaddress">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.QueryAddress"
android:usesCleartextTraffic="true"
>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<string name="app_name">queryAddress</string>
<string name="placeholder">请输入手机号</string>
<string name="location_button">查询号码归属地</string>
</resources> <?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="AppCode">d2d097126c45d4d6eb62c7dd330c8756</string>
</resources>
然后主程序的实现MainActivity.java:
package com.example.queryaddress;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText edit_mobile;
private Button location_button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_mobile = this.findViewById(R.id.edit_mobile);
location_button = this.findViewById(R.id.location_button);
location_button.setOnClickListener(this);
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public void onClick(View v) {
String phone = edit_mobile.getText().toString().trim();
if("".equals(phone)){
Toast.makeText(this, "手机号不能为空", Toast.LENGTH_LONG).show();
return;
}
switch (v.getId()) {
case R.id.location_button:
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
//用url这样拼接其实也是相当于默认走了get请求,不一定非得用HttpGet才能走get请求
URL url = new URL("https://api.topthink.com/telecom/location?phone="+phone);
//exception2
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
//setDoOutput()默认是false,需要手动设置为true,完了就可以调用getOutputStream()方法从服务器端获得字节输出流。
conn.setDoOutput(true);
String AppCode = getResources().getString(R.string.AppCode);
//按照接口文档:在请求Header中添加的Authorization字段,配置值为“AppCode + 半角空格 +AppCode值”。
conn.setRequestProperty("Authorization", "AppCode "+AppCode);
InputStream response = conn.getInputStream();
String json=new String( StreamTool.getBytes(response));
System.out.println( "服务端响应数据:"+json);
//解析json数据
/*
*
* {
"code": 0,
"message": "Return Successd!",
"data": {
"province": "上海",
"city": "上海",
"areacode": "021",
"zip": "200000",
"company": "移动",
"card": ""
}
}
* */
//最外层是json对象
JSONObject jsonObject = new JSONObject(json);
int code=jsonObject.getInt("code");
String message=jsonObject.getString("message");
if(code==0){
//里面的data还是一个对象
JSONObject data= jsonObject.getJSONObject("data");
String province= data.getString("province");
String city=data.getString("city");
String areacode=data.getString("areacode");
String zip=data.getString("zip");
String company=data.getString("company");
String card=data.getString("card");
String Row=province+" "+city+" "+areacode+" "+zip+" "+company+" "+card;
Toast.makeText(this, "获取到归属地信息:"+Row, Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "json解析异常", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}依赖StreamTool.java:
package com.example.queryaddress;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTool {
public static byte[] getBytes(InputStream is) throws Exception{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!=-1){
bos.write(buffer, 0, len);
}
is.close();
bos.flush();
byte[] result = bos.toByteArray();
return result;
}
}最后部署测试
ok,没有任何问题
关键字词:webservice,android,归属地
下一篇:46_多线程下载文件的原理