服务器返回的数据,Android端无法正常接收,显示为null
Android端login代码
public class Login {
private static final String TAG = "Dao";
/*登录*/
public int login(Context context, String userid, String userpassword){
final int[] msgs = {0};
String url = "http://169.254.240.137:8080/user/login1";
OkHttpClient client = new OkHttpClient();
Gson gson = new Gson();
// 构造要提交的数据
User myObject = new User(userid, userpassword);
// 将Java对象转换成JSON字符串
String jsonStr = gson.toJson(myObject);
// 构建HTTP请求
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
// 发送HTTP请求并处理响应结果
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("response","失败");
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String responseBody = response.body().string();
User result = new Gson().fromJson(responseBody,User.class);
// 获取解析结果
Log.d("respose", result.getUserid());
String code = result.getUserid();
// 处理解析结果
// ...
if (code.equals(userid)) {
msgs[0] = 1; //密码正确
} else{
msgs[0] = 2; //密码错误
}
} else {
// 打印错误信息
throw new IOException("Unexpected code " + response);
}
}
});
return msgs[0];
}
}
服务器端代码
@RequestMapping("/login1")
public User login(@RequestBody User user){
User user1 = coexistService.login(user.getUserid(), user.getUserpassword());
System.out.println(user1);//这里可以从数据库中查找到Android传来的用户信息
return user1;
}
使用的okhttp,服务器端可以接收消息并且处理,但是客服端无法收到,错误为404