【问题标题】:Getting Http response from server after posting data发布数据后从服务器获取 Http 响应
【发布时间】:2015-05-01 21:37:07
【问题描述】:

基本上,我有一个注册表单,用户会在其中提示输入电子邮件、用户名和密码。完成此表单后,所有数据都通过 POST 请求传输到数据库。到目前为止,一切都很好。现在我想从服务器获得响应,例如您已注册或此电子邮件/用户名已在使用中。 {"status"="....","message"="...."} 由 PHP 在服务器端完成。为了更清楚,我想取回作为“消息”的 Http 响应正文。我能找到的只是获取“状态”,即状态代码。

这是我的代码。

 public class MainActivity extends ActionBarActivity {
 EditText emailText;
 EditText usernameText;
 EditText passwordText;
 Button btn;
 User user;
 static String locale;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    emailText = (EditText) findViewById(R.id.emailText);
    usernameText = (EditText) findViewById(R.id.usernameText);
    passwordText = (EditText) findViewById(R.id.passwordText);
    btn = (Button) findViewById(R.id.button);
    final String username = usernameText.getText().toString();
    locale = getResources().getConfiguration().locale.getCountry();
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch(v.getId()){
                case R.id.button:
                    if(!validate())

                        Toast.makeText(getBaseContext(), "Enter some 
     data!", Toast.LENGTH_LONG).show();
                    // call AsynTask to perform network operation on 
     separate thread
                    new  HttpAsyncTask().execute("....");

                    break;
            }
        }
    });
}

public static String POST(String url, User user) {
    InputStream inputStream = null;
    String result = "";


    //Built the object
    JSONObject jsonObject = new JSONObject();
    try {

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        jsonObject.accumulate("email", user.getEmail());
        jsonObject.accumulate("username", user.getUsername());
        jsonObject.accumulate("password", user.getPassword());
        jsonObject.accumulate("location",locale);

        json = jsonObject.toString();

        StringEntity se = new StringEntity(json);
        httpPost.setEntity(se);

        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");


        HttpResponse httpResponse = httpClient.execute(httpPost);
        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();
        Log.d("testing",inputStream.toString());
        Log.d("test", httpResponse.toString());
        StatusLine statusLine = httpResponse.getStatusLine();
        Log.d("test", httpResponse.toString());




        int statusCode = statusLine.getStatusCode();
        if(statusCode == 200) {
            // 10. convert inputstream to string
            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                //String resp_body = 
      EntityUtils.toString(httpResponse.getEntity());
                //Log.d("resp_body", resp_body.toString());
                //JSONObject jsobj = new JSONObject(resp_body);
                HttpEntity resEntity = httpPost.getEntity();


            }else
                result = "Did not work!";
        }

    } catch (Exception e) {
        e.printStackTrace();



    }
    return result;
   }
   private class HttpAsyncTask extends AsyncTask<String, Void, String>   
   {
    @Override
    protected String doInBackground(String... urls) {

        user = new User();
        user.setUsername(usernameText.getText().toString());
        user.setPassword(passwordText.getText().toString());
        user.setEmail(emailText.getText().toString());




        return POST(urls[0],user);


    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Data Sent!", 
   Toast.LENGTH_LONG).show();

        Intent i = new Intent(MainActivity.this,SecondActivity.class);
        i.putExtra("username",usernameText.getText().toString());
        startActivity(i);
    }
 }

 private boolean validate(){
    if(usernameText.getText().toString().trim().equals(""))
        return false;
    else if(passwordText.getText().toString().trim().equals(""))
        return false;
    else if(emailText.getText().toString().trim().equals(""))
        return false;
    else
        return true;
}
private static String convertInputStreamToString(InputStream   
inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new   
InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;


    inputStream.close();
    return result;

 }

 }

【问题讨论】:

  • 请显示您的 HttpAsyncTask 在后台执行的操作
  • 您应该能够在异步调用中获取 HTTP 响应的内容并返回消息
  • convertInputStreamToString() 应该可以工作,EntityUtils.toString(httpResponse.getEntity()); 也可以。你只需要其中之一。不要同时使用两者。
  • Log.d("testing",inputStream.toString()); 你为什么不告诉这个声明传达了什么? Log.d("test", httpResponse.toString());。还有这个?
  • result = "Exception: " + e.getMessage(); 将其添加到 POST 函数中的 catch 块中。

标签: android json


【解决方案1】:

我建议您使用Retrofit 将 json 发布到您的服务器。 它是一个 Web 服务库,简化了 android 和 REST Web 服务之间的大量通信。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多