参考链接:【Android -- 网络请求】网络请求(Okhttp)_51CTO博客_android 网络请求
项目中需要通过发送网络请求获取需要显示的数据内容
请求地址和requestbody如上图所示
//网络请求用 implementation 'com.squareup.okhttp3:okhttp:4.9.3'
代码实现如下:
private void postRequest(JSONArray setCodeParam,JSONArray codeParam,int target){
MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
JSONObject requestObj = new JSONObject();
try {
JSONObject targetObj = new JSONObject();
targetObj.put("Target",target);
requestObj.put("Head",targetObj);
JSONArray colArray = new JSONArray();
colArray.put("COL1");
colArray.put("COL2");
requestObj.put("WantCol",colArray);
requestObj.put("Setcode",setCodeParam);
requestObj.put("Code",codeParam);
} catch (JSONException e) {
e.printStackTrace();
}
String requestBody = requestObj.toString();
Request request = new Request.Builder()
.url("http://xxxxx.xxxxx.com:0000/XXXXX?Entry=XXXXXXXXXXX")
.post(RequestBody.create(mediaType, requestBody))
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
String responseStr = response.body().string();
if(responseStr == null || responseStr.isEmpty())
return;
JSONObject responseObj = new JSONObject(responseStr);
......
Log.d(LOG_TAG, "onResponse: " + responseStr);
} catch (JSONException | NumberFormatException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call call, IOException e) {
Log.d(LOG_TAG, "onFailure: " + e.getMessage());
}
});
}