目录
一、前言
公司要求使用原生方式请求后端API接口(SpringBoot),在此做个记录。
二、后端
使用Mybatis-Plus查询MySQL单条数据,返回JSON格式到Android端。后端Controller代码如下:
@ResponseBody
@PostMapping(value = "/patch")
public AdConfigBean selectConfigByPkgName(@RequestParam("gkpn") String pkgName) {
return adconfigService.getOne(new QueryWrapper<AdConfigBean>()
.select("*")
.eq("pkg_name", pkgName), false);
}
三、Android端
(1)HTTP限制访问
Android对HTTP协议的请求已经不支持了,需要进行放行配置。先创建XML,再到AndroidManifest.xml配置文件中引用。
——network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true"/>
</network-security-config>
——AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.demo">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config"
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.Demo"
tools:targetApi="n">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
(2)XML页面布局
布局为两个控件,单击按钮,请求成功,文本框展示后端返回的JSON数据。
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
<Button
android:text="发送POST"
android:id="@+id/btn_sendPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
(3)HttpURLConnection工具类代码
public class NetworkUtil {
public static String doGet(String urlPath) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(urlPath).openConnection();
conn.setRequestMethod("GET");
if (200 == conn.getResponseCode()) {
return new BufferedReader(new InputStreamReader(conn.getInputStream())).readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
return "{ \"success\": false,\n \"errorMsg\": \"后台服务器开小差了!\",\n \"result\":{}}";
}
public static String doPost(String urlPath, HashMap<String, String> paramsMap) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(urlPath).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
StringBuilder result = new StringBuilder();
for (HashMap.Entry<String, String> entity : paramsMap.entrySet()) {
result.append("&").append(entity.getKey()).append("=").append(entity.getValue());
}
conn.getOutputStream().write(result.substring(1).getBytes());
if (200 == conn.getResponseCode()) {
return new BufferedReader(new InputStreamReader(conn.getInputStream())).readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
return "{ \"success\": false,\n \"errorMsg\": \"后台服务器开小差了!\",\n \"result\":{}}";
}
}
(4)MainActivity代码
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
TextView tvShow = findViewById(R.id.tv_show);
Button btnSendPost = findViewById(R.id.btn_sendPost);
btnSendPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
HashMap<String, String> paramsMap = new HashMap<>();
paramsMap.put("gkpn", "com.time.hxzbyx.meta");
new Thread(new Runnable() {
@Override
public void run() {
String resultJson = NetworkUtil.doPost("http://www.wugua.com.cn/patch", paramsMap);
runOnUiThread(new Runnable() {
@Override
public void run() {
tvShow.setText(resultJson);
Log.i("resultJson", resultJson);
}
});
}
}).start();
}
});
}
}
四、效果测试
五、总结
仅自己学习记录,如有错误,敬请谅解~,谢谢~~~