gpt4 book ai didi

android - POST 与 Android 改造

转载 作者:IT老高 更新时间:2023-10-28 22:26:11 28 4
gpt4 key购买 nike

我是 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(我假设此调用应该异步发生?):

我用下面的方法做了一个接口(interface):

    @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 格式数据 block 。如果有人能指出我正确的方向,那将不胜感激。提前谢谢你

最佳答案

Retrofit 的好处之一是不必自己解析 JSON。你应该有类似的东西:

service.login(email, password, new Callback<User>() { 
@Override
public void failure(final RetrofitError error) {
android.util.Log.i("example", "Error, body: " + error.getBody().toString());
}
@Override
public void success(User user, Response response) {
// Do something with the User object returned
}
}
);

其中 User 是类似 POJO 的地方

public class User {
private String name;
private String email;
// ... etc.
}

并且返回的 JSON 具有与 User 类匹配的字段:

{
"name": "Bob User",
"email": "bob@example.com",
...
}

如果您需要自定义解析,则可以在使用 .setConverter(Converter converter) 设置 REST 适配器的转换器时进行。 :

The converter used for serialization and deserialization of objects.

关于android - POST 与 Android 改造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19796235/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com