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

时间:2014-12-19 16:41:30

标签: java android json

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

我的问题是

  1. 如何将这个由php echo发送的json消息存储到android app中的变量中?
  2. 我如何解析json并使用数据构建一个switch case?
  3. 我在某个时候提出了类似的问题并被告知要使用AsyncTask,但我不明白为什么我需要使用它。

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

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

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

    我目前有像这样的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("");
            }
    
        }
    

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

1 个答案:

答案 0 :(得分:1)

使用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");
}