【发布时间】:2013-11-16 18:06:46
【问题描述】:
我是 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 格式数据块。如果有人能指出我正确的方向,那将不胜感激。提前谢谢你
【问题讨论】:
-
您在哪个 android API 中工作?
-
@BlueGreen 我正在使用我公司自己的 API,所以我正在尝试使用 Retrofit 进行 GET/POST 调用
-
我现在正在用 Retrofit 测试我的 REST,和你做同样的事情,但我还没有准备好给你一个完整的答案。对于初学者,请尝试使用 Callback
- 这应该会给你一个原始数据。您的代码总体上看起来是正确的 -
我目前面临同样的问题。你设法让它工作了吗?
-
你让它工作了吗?我正在做同样的事情,并且在尝试使用 FormUrlEncoded 的回调执行异步 POST 时遇到了 IllegalArgumentException - stackoverflow.com/questions/22572301/…
标签: android android-asynctask android-networking androidhttpclient retrofit