在Android Studio中发送数据后从服务器获取JSON响应

时间:2018-11-02 11:27:18

标签: android android-asynctask

我有注册活动,并使用Async taks将用户详细信息发送到服务器。如果注册成功或失败,我想从服务器获取响应。

这是我的async task

的代码
class backgroundTask_register_activity extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... voids) {

        String url = "http://13.232.207.9/php/register.php";

        final List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("user_id",user_id));
        parameters.add(new BasicNameValuePair("user_fullname",reg_user_fullname.getText().toString()));
        parameters.add(new BasicNameValuePair("user_name",reg_user_name.getText().toString()));
        parameters.add(new BasicNameValuePair("user_email",reg_user_email.getText().toString()));
        parameters.add(new BasicNameValuePair("user_mobile",reg_user_mobile.getText().toString()));
        parameters.add(new BasicNameValuePair("user_city",reg_user_city.getText().toString()));
        parameters.add(new BasicNameValuePair("user_password",reg_user_password.getText().toString()));
        parameters.add(new BasicNameValuePair("user_dob",DOB_textView.getText().toString()));
        parameters.add(new BasicNameValuePair("user_gender",reg_user_gender));

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);

        try {
            httppost.setEntity(new UrlEncodedFormEntity(parameters));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                Toast toast = Toast.makeText(getApplicationContext(),EntityUtils.toString(entity),Toast.LENGTH_SHORT);
                toast.show();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

php的响应为{"success":1,"Message":"User added successfully"}

所以我想显示相同的敬酒通知。要做出回应,我必须进行哪些更改?

但是我的代码强制关闭了应用程序:

他是错误日志:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: com.prasaurus.app.psa_b2c_app, PID: 10201
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:309)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:200)
        at android.os.Handler.<init>(Handler.java:114)
        at android.widget.Toast$TN.<init>(Toast.java:356)
        at android.widget.Toast.<init>(Toast.java:101)
        at android.widget.Toast.makeText(Toast.java:266)
        at com.prasaurus.app.psa_b2c_app.RegisterActivity$backgroundTask_register_activity.doInBackground(RegisterActivity.java:145)
        at com.prasaurus.app.psa_b2c_app.RegisterActivity$backgroundTask_register_activity.doInBackground(RegisterActivity.java:119)
        at android.os.AsyncTask$2.call(AsyncTask.java:295)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
        at java.lang.Thread.run(Thread.java:818) 

3 个答案:

答案 0 :(得分:1)

您需要在try块中添加以下内容。

 try {
            httppost.setEntity(new UrlEncodedFormEntity(parameters));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
               Toast toast = Toast.makeText(getApplicationContext(),EntityUtils.toString(entity),Toast.LENGTH_SHORT);
               toast.show();
            }
      }

您可以使用Toast.LENGTH_LONG来做长土司面包。

答案 1 :(得分:0)

import sys import matplotlib import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import numpy from numpy.random import randn from scipy import array, newaxis import matplotlib.ticker as ticker ## plot: fig = plt.figure("2D plot") contour = plt.tricontourf(X, Y, Z, 200, cmap="bwr") def fmt(x, pos): a, b = '{:.2e}'.format(x).split('e') b = int(b) return r'${} \times 10^{{{}}}$'.format(a, b) plt.colorbar(contour, format=ticker.FuncFormatter(fmt)) plt.show() 之后和HttpResponse response = httpclient.execute(httppost)语句之前,解析所需的Json响应部分,将其写入字符串变量,并创建一个传递此变量作为参数的Toast。

答案 2 :(得分:0)

使用服务器的响应添加Toast,

 try {
            httppost.setEntity(new UrlEncodedFormEntity(parameters));
            HttpResponse response = httpclient.execute(httppost);
        Toast.makeText(getApplicationContext(),"Response: "+response ,Toast.LENGTH_SHORT).show();


        }