Android 通过安卓系统改造发布

Android 通过安卓系统改造发布,android,android-asynctask,android-networking,androidhttpclient,retrofit,Android,Android Asynctask,Android Networking,Androidhttpclient,Retrofit,我对Android编程和改型工作还不熟悉。我在这个问题上做了很多研究,但是还没有找到一个适合我需要的解决方案。我正在使用我们的API并尝试发出POST请求。我通过以下非改装代码成功实现了这一点: private class ProcessLogin extends AsyncTask<Void, String, JSONObject> { private ProgressDialog pDialog; String email,password; p

我对Android编程和改型工作还不熟悉。我在这个问题上做了很多研究,但是还没有找到一个适合我需要的解决方案。我正在使用我们的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));
        }

    }
}
私有类ProcessLogin扩展异步任务{
私人对话;
字符串电子邮件,密码;
受保护的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=新建进度对话框(LoginActivity.this);
pDialog.setTitle(“联系服务器”);
设置消息(“登录…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
受保护的JSONObject doInBackground(无效…参数){
httpurl连接;
OutputStreamWriter请求=null;
URL=null;
字符串响应=null;
String parameters=“username=“+email+”&password=“+password;
尝试
{
url=新url(“http://.../api/login");
connection=(HttpURLConnection)url.openConnection();
connection.setDoOutput(真);
connection.setRequestProperty(“内容类型”、“应用程序/x-www-form-urlencoded”);
connection.setRequestMethod(“POST”);
请求=新的OutputStreamWriter(connection.getOutputStream());
请求。写入(参数);
request.flush();
request.close();
字符串行=”;
InputStreamReader isr=新的InputStreamReader(connection.getInputStream());
BufferedReader读取器=新的BufferedReader(isr);
StringBuilder sb=新的StringBuilder();
而((line=reader.readLine())!=null)
{
sb.追加(第+行“\n”);
}
//登录过程后来自服务器的响应将存储在响应变量中。
response=sb.toString();
//您可以在此处执行UI操作
isr.close();
reader.close();
}
捕获(IOE异常)
{
//错误
}
System.out.println(响应);
JSONObject jObj=null;
//尝试将字符串解析为JSON对象
试一试{
jObj=新的JSONObject(响应);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
//返回JSONObject
返回jObj;
}
受保护的void onPostExecute(JSONObject json){
字符串状态=(字符串)json.optJSONArray(“用户”).optJSONObject(0.optJSONObject(“用户”).optString(“登录”);
pDialog.disclose();
if(status.equals(“Failed”)){
loginMessage.setText(“登录失败”);
}
else if(状态等于(“成功”)){
loginMessage.setText(“成功!”);
startActivity(新意图(getApplicationContext(),DActivity.class));
}
}
}
现在,我正试图通过改型获得相同的结果,但我不确定如何使用回调从我们的API中获取JSON(我假设这个调用应该异步进行):

我使用以下方法制作了一个接口:

    @FormUrlEncoded
@POST("/login")
public void login(@Field("username") String username, @Field("password") String password, Callback<JSONObject> callback);
@FormUrlEncoded
@POST(“/登录”)
公共无效登录(@Field(“用户名”)字符串用户名,@Field(“密码”)字符串密码,回调);
并在活动的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) {

            }
        }
        );
service.login(电子邮件、密码、新回调(){
@凌驾
公共无效失败(最终错误){
android.util.Log.i(“示例”,“错误,正文:”+Error.getBody().toString());
}
@凌驾
公共无效成功(JSONObject arg0,响应arg1){
}
}
);

然而,这并没有达到预期的效果,我真的认为我没有正确地处理这个问题。我希望能够向我们的服务器发送一个帖子,它会发回一块关于该用户的JSON格式的数据。如果有人能给我指出正确的方向,我将不胜感激。提前感谢

改型的好处之一是不必自己解析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
        }
    }
);
返回的JSON具有与
User
类匹配的字段:

{
  "name": "Bob User",
  "email": "bob@example.com",
  ...
}
如果需要自定义解析,则在设置REST适配器的转换器时使用以下命令:

用于对象序列化和反序列化的转换器


似乎改型与
@POST
@FormUrlEncoded
有问题。如果我们进行同步,它工作得很好,但是如果进行异步,它就失败了

若@mike问题是反序列化对象,那个么用户类应该是

public class User {
     @SerializedName("name")
     String name;

     @SerializedName("email")
     String email;
}
接口类

@FormUrlEncoded
@POST("/login")
void login(@Field("username") String username, @Field("password") String password, Callback<User> callback);

您使用的是哪种android API?@BlueGreen我使用的是我公司自己的API,所以我正在尝试使用改型来进行GET/POST调用。我现在正在使用改型来测试我的其余部分,做与您相同的事情,但我还没有准备好给您一个完整的答案。对于初学者来说,尝试使用回调-这将为您提供原始数据。您的代码在generalI中看起来是正确的,我目前也面临同样的问题。你设法让它工作了吗?你让它工作了吗?我也在做同样的事情,在尝试使用FormUrlEncoded的回调进行异步POST时,我得到了一个IllegalArgumentException,这是一个很好的例子,等式的所有“部分”都是d
@FormUrlEncoded
@POST("/login")
void login(@Field("username") String username, @Field("password") String password, Callback<User> callback);
@FormUrlEncoded
@POST("/login")
void login(@Field("username") String username, @Field("password") String password, Callback<UserResponse> callback);
public class UserResponse {

@SerializedName("email")
String email;

@SerializedName("name")
String name;

}