如何调用php文件并存储json输出

时间:2021-09-10 14:04:32

I am developing an android app, I have run into a situation where the app will use an API to send some data to the php webservice and the webservice will greate some json encoded message which will be echoed back.

我正在开发一个Android应用程序,我遇到了这样一种情况:应用程序将使用API​​将一些数据发送到php webservice,而webservice将会更新一些json编码的消息,这些消息将被回显。

My question is

我的问题是

  1. How Do I store this json message that was sent by php echo into a variable in the android app?
  2. 如何将这个由php echo发送的json消息存储到android应用程序中的变量中?

  3. How Do I then go about parsing the json and use the data to construct a switch case?
  4. 然后我如何解析json并使用数据构建一个switch case?

I had raised a similar question sometime back and was told to use AsyncTask but what I don't understand is why would I need to use it.

我曾经提出类似的问题并被告知使用AsyncTask但我不明白为什么我需要使用它。

The sample json response that will be sent by the phpwebservice is

将由phpwebservice发送的示例json响应是

{"error":false,"message":"New user created"}

I want to be able to get the error variable and decide if there is any error and also get the message in a variable and display it to the user in the app.

我希望能够获取错误变量并确定是否有任何错误,并在变量中获取消息并将其显示给应用程序中的用户。

I currently have the android signup.java code like this

我目前有像这样的android signup.java代码

public void post() throws UnsupportedEncodingException
    {
        // Get user defined values
        uname = username.getText().toString();
        email   = mail.getText().toString();
        password   = pass.getText().toString();
        confirmpass   = cpass.getText().toString();
        phone = phn.getText().toString();

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse httpResponse = null;
        HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
        if (password.equals(confirmpass)) {
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
                nameValuePairs.add(new BasicNameValuePair("uname", uname));
                nameValuePairs.add(new BasicNameValuePair("pass", password));
                nameValuePairs.add(new BasicNameValuePair("email", email));
                nameValuePairs.add(new BasicNameValuePair("phone", phone));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                httpResponse = httpclient.execute(httppost);
                //Code to check if user was successfully created
                final int statusCode = httpResponse.getStatusLine().getStatusCode();
                switch (statusCode)
                {
                    case 201:
                        Toast.makeText(getBaseContext(), "Successfully Registered", Toast.LENGTH_SHORT).show();
                        break;
                    case 400:
                        Toast.makeText(getBaseContext(), "Username already taken", Toast.LENGTH_SHORT).show();
                        username.setText("");
                        break;
                    default:
                        Toast.makeText(getBaseContext(), "Unknown error occurred", Toast.LENGTH_SHORT).show();
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else
        {
            Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
            //Reset password fields
            pass.setText("");
            cpass.setText("");
        }

    }

While this checks the http header code and might work( I havent tested it out) I want to use the jsnon response and do the handling using it.

虽然这检查http头代码并可能工作(我没有测试它)我想使用jsnon响应并使用它进行处理。

1 个解决方案

#1


1  

Use java-json:

HttpURLConnection urlConnection = (HttpURLConnection) (uri.toURL().openConnection());
urlConnection.setConnectTimeout(1500);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", uname));
params.add(new BasicNameValuePair("pass", password));
params.add(new BasicNameValuePair("email", email));

OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
    new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

urlConnection.connect();
if(urlConnection.getResponseCode() == 200){
    InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
    BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;
    while ((inputStr = streamReader.readLine()) != null)
        responseStrBuilder.append(inputStr);
    JSONObject json = new JSONObject(responseStrBuilder.toString());
    String message = json.getString("message");
}

#1


1  

Use java-json:

HttpURLConnection urlConnection = (HttpURLConnection) (uri.toURL().openConnection());
urlConnection.setConnectTimeout(1500);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", uname));
params.add(new BasicNameValuePair("pass", password));
params.add(new BasicNameValuePair("email", email));

OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
    new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

urlConnection.connect();
if(urlConnection.getResponseCode() == 200){
    InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
    BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;
    while ((inputStr = streamReader.readLine()) != null)
        responseStrBuilder.append(inputStr);
    JSONObject json = new JSONObject(responseStrBuilder.toString());
    String message = json.getString("message");
}