您好我使用GET请求成功从我的数据库中检索数据。
在我的数据库中,我有3个字段 - employeeId, employeeName, userPin
。
然而,当我收到回复消息时,从我的Android应用程序中,我只想看到userPin
。
这是我的代码:
String url = "http://xxx.xx.xxx.xxx:7001/engAppApi/webservices/usersTable/"+ id;
URL object = new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Bearer " +token);
con.setRequestProperty
con.setRequestMethod("GET");
Log.d("responsecode", String.valueOf(con.getResponseCode()));
Log.d("responsemessage", String.valueOf(con.getHeaderFields()));
if (con.getResponseCode() == HttpsURLConnection.HTTP_OK || con.getResponseCode() == HttpsURLConnection.HTTP_ACCEPTED ) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((line=br.readLine()) != null) {
userPinRetrieved+=line;
}
}
} catch (Exception e) {
Log.v("ErrorAPP", e.toString());
}
return "";
}
POSTMAN结果:
<?xml version="1.0" encoding="UTF-8"?>
<usersTable>
<employeeId>2</employeeId>
<employeeName>Tom Williams </employeeName>
<userPin>666666</userPin>
</usersTable>
任何人都可以帮助我吗?
答案 0 :(得分:0)
我建议你使用retrofit来安装android,因为很容易只解析必要的值。例如,在我的项目中,我需要获取用户统计信息。为此,我创建了Model of Values:
@SerializedName("user_stats")
@Expose
private List<MyStatsModel> myStats = null;
使用获取方法
public List<MyStatsModel> getMyStats() {
return myStats;
}
并且在我的onResponse方法中使用这些值轻松地做出任何想法:
@Override
public void onResponse(Call<Model> call, Response<Model> response) {
if(response.isSuccessful()) {
if(response.body().getMyStats() == null) {
emptyTextStats.setVisibility(View.VISIBLE);
statsRecyclerView.setVisibility(View.GONE);
}
else {
Log.d("tag", "stats response null" + MainActivity.getSid());
emptyTextStats.setVisibility(View.GONE);
statsRecyclerView.setVisibility(View.VISIBLE);
statsAdapter.updateStats(response.body().getMyStats());
}
}
}
此外,这个site将帮助您将JSON解析为Model和java对象