我想使用Android客户端和Glassfish 4.1.1服务器(通过REST服务进行通信)实现基本身份验证。 该服务运行良好(由POSTMAN和另一个C#-Client验证),但在Android上,它让我疯狂了。 似乎在服务器端接收到对象发送为'null',在Android端也抛出恼人的“EOFException”。 服务器端(工作正常)
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Account validate(Account acc)
{
Account a = null;
a = Database.getInstance().getAccountByUserPw(acc);
return a;
}
Android客户端:
public Account postData(String JSONtoSend)
{
URL url;
Account get = new Account();
try {
url = new URL("http://192.xxx.xxx.x:18080/HolidayOutServer/webresources/validateacc");
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setRequestMethod("POST");
urlCon.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlCon.setRequestProperty("Accept", "application/json; charset=UTF-8");
urlCon.setDoOutput(true); // to be able to write.
urlCon.setDoInput(true); // to be able to read.
OutputStreamWriter out = new OutputStreamWriter(urlCon.getOutputStream());
out.write(JSONtoSend);
ObjectInputStream ois = new ObjectInputStream(urlCon.getInputStream());
get = (Account) ois.readObject();
return get;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return get;
}
在此范围内调用:
class help extends AsyncTask<String, Void, Account>
{
@Override
protected Account doInBackground(String... params) {
return postData(new Gson().toJson(new Account("aleqs", "lexx", -2)));
}
}
问题简而言之:
有人可以帮忙吗? 提前致谢, 约翰。
答案 0 :(得分:0)
好的,我设法在下班后找到解决方案。 这段代码适合我:
try( DataOutputStream wr = new DataOutputStream( urlCon.getOutputStream())) {
wr.write(new Gson().toJson(new Account("aleqs", "lexx", -2)).getBytes());
}
Reader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char)c);
response = sb.toString();
return response;
} catch (IOException e) {
e.printStackTrace();
}
return response;
更改&#34; donInBackGround&#34;的返回类型to String并让helper类扩展-String,Void,String-。 最重要的是:检查您在客户端的属性(例如,ID,名称,......)是否与来自SERVER SIDE的属性相匹配。 考虑上限锁等等。 干杯!