我是 Android 编程和使用 Retrofit 的新手。我已经对此主题进行了大量研究,但无法找到适合我需求的解决方案。我正在使用我们的 API 并尝试发出 POST 请求。我使用以下非改造代码成功地实现了这一点:
private class ProcessLogin extends AsyncTask<Void, String, JSONObject> {
private ProgressDialog pDialog;
String email,password;
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected JSONObject doInBackground(Void... params) {
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = "username="+email+"&password="+password;
try
{
url = new URL("http://.../api/login");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
System.out.println(response);
JSONObject jObj = null;
// Try to parse the string to a JSON Object
try {
jObj = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return the JSONObject
return jObj;
}
protected void onPostExecute(JSONObject json) {
String status = (String) json.optJSONArray("users").optJSONObject(0).optJSONObject("user").optString("login");
pDialog.dismiss();
if (status.equals("Failed")) {
loginMessage.setText("Login Failed");
}
else if (status.equals("Success")) {
loginMessage.setText("Success!");
startActivity(new Intent(getApplicationContext(), DActivity.class));
}
}
}
现在,我正在尝试使用 Retrofit 获得相同的结果,但我不确定如何使用回调从我们的 API 中获取 JSON(我假设这个调用应该异步发生?):
我用以下方法制作了一个接口:
@FormUrlEncoded
@POST("/login")
public void login(@Field("username") String username, @Field("password") String password, Callback<JSONObject> callback);
并在我的 Activity 的 onCreate 方法中实例化了 RestAdapter 等。当用户按下“登录”按钮(输入用户名和密码后)时,在按钮的 onClick 方法中调用以下内容:
service.login(email, password, new Callback<JSONObject>() {
@Override
public void failure(final RetrofitError error) {
android.util.Log.i("example", "Error, body: " + error.getBody().toString());
}
@Override
public void success(JSONObject arg0, Response arg1) {
}
}
);
然而,这并没有按预期工作,我真的认为我没有正确处理这个问题。我希望能够向我们的服务器发送一个 POST,它会发回关于该用户的 JSON 格式数据块。如果有人能指出我正确的方向,那将不胜感激。先感谢您