发布数据后从服务器获取Http响应

时间:2015-05-01 13:34:36

标签: android json

基本上,我有一个注册表单,用户提示输入电子邮件,用户名和密码。完成此表单后,所有数据都将通过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;

 }

 }

1 个答案:

答案 0 :(得分:0)

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