目录
一、实现效果
输入男方星座和女方星座,点击查询,出现配对结果。
二、注册聚合网并申请key
首先,在聚合网https://www.juhe.cn/进行注册,并进行实名认证,即可免费申请天气预报、星座配对等API接口。
本文将以星座配对为例,介绍聚合数据API的申请。在首页搜索到星座配对的API,并点击“立即使用”。申请成功后界面显示如下。
查看API文档下方的请求示例,这个示例的URL在后面的java代码中需要用到。
点击右上角的个人中心,在左侧的数据中心->我的API中查看请求KEY,这个在java代码中也需要使用到。
点击“测试”,可以在线测试你申请的API,输入相应值后,获得相应的JSON数据示例。
JSON数据示例如下:
三、Android Studio具体实现
3.1 导入json解析所需依赖包
JSON解析需要用到和json-lib-2.4-jdk15.jar相关的7个包,可以在https://mvnrepository.com/进行下载。也可以找我上传的资源https://download.csdn.net/download/ycsss/13385836下载。
下载完成后,导入app/libs如下。也可以直接放到文件夹中,如上图所示。
3.2 构造显示界面layout
布局是嵌套的LinearLayout,分别放置了两个TextView标签,两个EditView,一个Button,和一个可垂直滚动的TextView。
activity_main.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:gravity="center_horizontal"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal"
android:layout_margin="10dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男方星座:" />
<EditText
android:id="@+id/editText_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="3" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="女方星座:" />
<EditText
android:id="@+id/editText_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="3" />
</LinearLayout>
<Button
android:id="@+id/button_query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查询" />
<TextView
android:id="@+id/textView_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:scrollbars="vertical"/>
</LinearLayout>
</LinearLayout>
3.3 核心代码
这里只摘取了部分核心代码,完整代码见3.4。
3.3.1 使用HttpURLConnection向网页发送请求
HttpURLConnection connection = null;
url = new URL(API_URL + "key=" + API_KEY + "&men="
+ constellation1 + "&women=" + constellation2);
// 通过远程url连接对象打开一个连接,转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:8000毫秒
connection.setConnectTimeout(8000);
// 设置读取远程返回的数据时间:8000毫秒
connection.setReadTimeout(8000);
// 获取输入流
in = connection.getInputStream();
// 对获取到的输入流进行读取
reader = new BufferedReader(
new InputStreamReader(in));
// 存放数据
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
3.3.2 读取请求到的JSON数据并进行解析
JSON返回示例(可在聚合网API中查看,如2中的图片所示):
{
"reason": "success",
"result": {
"men": "白羊",
"women": "金牛",
"zhishu": "70",/*配对指数*/
"bizhong": "54:46",/*配对比重*/
"xiangyue": "4",/*两情相悦指数*/
"tcdj": "3",/*天长地久指数*/
"jieguo": "小吵小闹的一对 ",/*结果描述*/
"lianai": "白羊座性急,金牛座慢半拍,这两个星座在一起就像龟兔赛跑,牛儿永远跟在羊儿身后。你们在一起更多的互补作用,金牛座总是无怨无悔地为性急的白羊座收拾善后,默默地付出。有时你们也会像一对童心未泯的孩子,童心很重,在一定程度,牛儿还蛮依赖羊儿。",/*恋爱建议*/
"zhuyi": "白羊座和金牛座在一起,其实也是一对孩子气蛮重的组合,他们都有着童心未泯的个性。牛儿虽然很能容忍、不妒忌,但占有欲强,羊儿个性豪迈,喜欢交际,牛儿若爱上羊儿,可以在一定程度上给予对方更大的自由和空间。同时牛儿也不必时时为羊儿善后,不妨放开心胸促使不要学习平稳冷静,带着羊儿向前,在生活上学习取长补短。"/*注意事项*/
},
"error_code": 0
}
解析json:
//对获取到的JSON数据进行解析
protected String parseWithJSON(String response) {
String output = "";
try {
JSONObject jsonObject = new JSONObject(response);
int error_code = jsonObject.getInt("error_code");
if (error_code == 0) {
JSONObject resultObject = jsonObject.getJSONObject("result");
String men = resultObject.getString("men");
String women = resultObject.getString("women");
String matching = resultObject.getString("zhishu");
String proportion = resultObject.getString("bizhong");
String romance = resultObject.getString("xiangyue");
String everlasting = resultObject.getString("tcdj");
String result = resultObject.getString("jieguo");
String advice = resultObject.getString("lianai");
String attention = resultObject.getString("zhuyi");
output = "男方星座:" + men + "\n女方星座:" + women +
"\n配对指数:" + matching + "\n配对比重:" + proportion +
"\n两情相悦指数:" + romance + "\n天长地久指数:" + everlasting +
"\n结果描述:" + result + "\n恋爱建议:" + advice +
"\n注意事项:" + attention;
}
else {
output = "调用接口失败:" + jsonObject.getString("reason");
Log.d("调用接口失败:" , jsonObject.getString("reason"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return output;
}
3.3.3 使用子线程handler将结果显示在UI上
//子线程
private final Handler handler = new Handler(new Handler.Callback() {
public boolean handleMessage(Message msg) {
if (msg.what == SHOW_RESPONSE) {
String response = (String) msg.obj;
// 在这里进行UI操作,将结果显示到界面上
responseText.setText(response);
}
return false;
}
});
3.4 完整的MainActivity.java代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText constellation_male;
private EditText constellation_female;
private Button sendRequest;
private TextView responseText;
public static final int SHOW_RESPONSE = 0;
public static String API_URL = "http://apis.juhe.cn/xzpd/query?"; // 星座配对查询接口地址
public static String API_KEY = "输入你的请求key"; // 接口请求Key
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest = (Button) findViewById(R.id.button_query);
responseText = (TextView) findViewById(R.id.textView_result);
constellation_male = (EditText) findViewById(R.id.editText_male);
constellation_female = (EditText) findViewById(R.id.editText_female);
sendRequest.setOnClickListener(arg0 -> sendRequestWithHttpURLConnection()); //设置按钮监听
responseText.setMovementMethod(ScrollingMovementMethod.getInstance()); //设置文字框垂直滚动条
}
//使用HttpURLConnection向网页发送请求,并将解析结果返回子线程
protected void sendRequestWithHttpURLConnection() {
new Thread(() -> {
URL url;
HttpURLConnection connection = null;
InputStream in = null;
BufferedReader reader = null;
try {
// 完整URL示例,见参考在聚合网的请求示例("http://apis.juhe.cn/xzpd/query?key=你的请求&men=%E7%99%BD%E7%BE%8A&women=%E9%87%91%E7%89%9B");
// 将URL参数(男方星座、女方星座)转换为utf-8
String constellation1 = URLEncoder.encode(
constellation_male.getText().toString(), "utf-8");
String constellation2 = URLEncoder.encode(
constellation_female.getText().toString(), "utf-8");
// 创建远程url连接对象
url = new URL(API_URL + "key=" + API_KEY + "&men="
+ constellation1 + "&women=" + constellation2);
// 通过远程url连接对象打开一个连接,转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:8000毫秒
connection.setConnectTimeout(8000);
// 设置读取远程返回的数据时间:8000毫秒
connection.setReadTimeout(8000);
// 获取输入流
in = connection.getInputStream();
// 对获取到的输入流进行读取
reader = new BufferedReader(
new InputStreamReader(in));
// 存放数据
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
//System.out.println("response = " + response.toString());
//进行JSON解析
String output = parseWithJSON(response.toString());
Message message = new Message();
message.what = SHOW_RESPONSE;
// 将服务器返回的结果存放到Message中
message.obj = output;
handler.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();// 关闭远程连接
}
}
}).start();
}
//子线程
private final Handler handler = new Handler(new Handler.Callback() {
public boolean handleMessage(Message msg) {
if (msg.what == SHOW_RESPONSE) {
String response = (String) msg.obj;
// 在这里进行UI操作,将结果显示到界面上
responseText.setText(response);
}
return false;
}
});
//对获取到的JSON数据进行解析
protected String parseWithJSON(String response) {
String output = "";
try {
JSONObject jsonObject = new JSONObject(response);
int error_code = jsonObject.getInt("error_code");
if (error_code == 0) {
JSONObject resultObject = jsonObject.getJSONObject("result");
String men = resultObject.getString("men");
String women = resultObject.getString("women");
String matching = resultObject.getString("zhishu");
String proportion = resultObject.getString("bizhong");
String romance = resultObject.getString("xiangyue");
String everlasting = resultObject.getString("tcdj");
String result = resultObject.getString("jieguo");
String advice = resultObject.getString("lianai");
String attention = resultObject.getString("zhuyi");
output = "男方星座:" + men + "\n女方星座:" + women +
"\n配对指数:" + matching + "\n配对比重:" + proportion +
"\n两情相悦指数:" + romance + "\n天长地久指数:" + everlasting +
"\n结果描述:" + result + "\n恋爱建议:" + advice +
"\n注意事项:" + attention;
}
else {
output = "调用接口失败:" + jsonObject.getString("reason");
Log.d("调用接口失败:" , jsonObject.getString("reason"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return output;
}
}
3.5 添加网络访问权限
在AndroidManifest.xml中加入一行
<uses-permission android:name="android.permission.INTERNET"/>
以及
android:usesCleartextTraffic="true"
效果如图: