目前正在构建具有Web服务的Android应用程序。尝试使用okhttp3从SQL数据库获取数据,但我得到一个奇怪的响应,我无法弄明白。我在Laravel的API是:
public function getAccount(Request $request, User $user)
{
$email = $request->input('email');
//$response = Users::find($email);
$response = DB::table('users')->where('email', $email)->first();
$count = count($response);
if($count == 0) {
return Response::json([
'message' => 'An error occured',
], 401);
} else {
return Response::json([
'user' => $response->name,
'lastName' => $response->lastName,
'weight' => $response->weight,
'height' => $response->height,
'dob' => $response->DOB,
'email' => $response->email,
], 200);
}
我的Android代码是:
private void getDetails() {
Thread thread = new Thread(new Runnable(){
public void run() {
OkHttpClient client = new OkHttpClient();
// Json string with email and password
String bodyString = "{\n\t\"email\" : \"" + email +"\"\n}";
// Make HTTP POST request
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, bodyString);
Request request = new Request.Builder()
.url("http://192.168.1.100/CAB398/public/api/auth/getAccount")
.post(body)
.addHeader("accept", "application/json")
.addHeader("content-type", "application/json")
//.addHeader("cache-control", "no-cache")
//.addHeader("postman-token", "c3d60511-7e0f-5155-b5ad-66031ad76578")
.build();
// execute request
try {
Response response = client.newCall(request).execute();
String responseData = response.body().toString();
// Response code 200 means login details found in DB
if(response.code() == 200){
etfirstName.setText(responseData);
} else if(response.code() == 401){
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
//wait for thread to finish
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
问题是,我得到okhttp3.internal.http.RealResponseBody@b8a47c8
作为response.body().toString()
的回复。我使用postman测试了 API 调用,并获得了正确的响应:
{ “用户”: “乔”, “姓氏”: “史密斯”, “权重”:108, “高度”:179, “出生日期”: “1980年9月6日”, “电子邮件”:“为JoeSmith @ gmail.com“}
我认为我搞砸了请求。生成器,但我无法弄清楚这一点。
干杯 彼得