0

我是android新手,学习了一下。我有责任在 android 和 php 之间传递 json 对象。

我有这个代码来发送 json 对象以将 json 对象发送到服务器。它运作良好。它也印在吐司上。但是任何人都可以帮助我如何阅读和显示我的服务器对我的应用程序的响应吗?

我的代码看起来像

package com.test.webservice;


import android.util.Log;
import android.view.Menu;
import android.app.Activity;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        String path = "http://www.mysite.com/app.php";

        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
                                                                                // Limit
        HttpResponse response;
        JSONObject json = new JSONObject();
        try {
            HttpPost post = new HttpPost(path);
            json.put("service", "GOOGLE");
            json.put("name", "My Name");
            Log.i("jason Object", json.toString());
            post.setHeader("json", json.toString());
            StringEntity se = new StringEntity(json.toString());
            se.setContentEncoding((Header) new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(se);
            response = client.execute(post);
            /* Checking response */
            if (response != null) {
                InputStream in = response.getEntity().getContent(); // Get the
                                                                    // data in
                                                                        // the
                                                                        // entity
                String a = convertStreamToString(in);

                Toast.makeText(getApplicationContext(), 
                        a, Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }






    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

}
4

1 回答 1

1

response假设如果您有一个像下面这样在您身边调用的数组php,然后我假设您正在以这种方式将数据填充到该数组中:

$response = array();
$response["intvalue"] = 1234;
$response["stringmessage"] = "Data from the server";

echo json_encode($response);// Here you are echoing json response. So in the inputstream you would get the json data. You need to extract it over there and can display according to your requirement.

android端提取:

在这里,您需要通过以下方式将字符串(您在 toast 中显示的)转换为 json 对象:

JSONObject json = stringToJsonobj(a);  // a is your string response

int passedinteger = json.getInt("intvalue");
String passedStringValue = json.getString("stringmessage");

public JSONObject stringToJsonobj(String result)
    {
        JSONObject jObj = null;
            try {

            jObj = new JSONObject(result);          

        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());

        }

         return jObj; 
}

通过这种方式,您可以获得individual values(passedinteger, passedstringvalue)并显示在您想要的任何视图上。希望这可以帮助

于 2013-05-04T07:47:56.730 回答