0

我想从 Android 应用程序访问一个简单的 php web 服务。为了测试这一点,我创建了第一个使用 json 编码的 php Web 服务,并将其托管在本地主机上运行的 WAMPSERVER 中。

<?php
$string='{"name":"John Adams"}';
echo json_encode($string);
?>

为了访问这个 Web 服务,我创建了一个 Android http 客户端,如下所示。

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class JsonV01Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.0.2.2/json/phpjson.php");
    try {
       HttpResponse response = httpclient.execute(httppost);
       String str =  EntityUtils.toString(response.getEntity());

       JSONObject object = (JSONObject) new JSONTokener(str).nextValue();

       String name = object.getString("name");

       TextView tv = (TextView) findViewById(R.id.textView1);
       tv.append(name);
    }
    catch (JSONException e) {e.printStackTrace();}

    catch(Exception ex){ex.printStackTrace();}

    }
}

我添加了互联网权限,但这只会提供空白屏幕。我知道这个问题很简单,但我无法解决。请帮忙,错误是什么以及如何纠正。

提前致谢!

4

1 回答 1

0

那我怎么总是这样做!

                try {
URL url2 = new URL("http://10.0.2.2/2010/phpfile.php");
                BufferedReader in = new BufferedReader(new InputStreamReader(url2.openStream()));
                String line ="";
                while ((line = in.readLine()) != null) {

                    JSONArray ja = new JSONArray(line);
                    values = new String [ja.length()];          

                    // fetching data
                    for (int i=0; i < ja.length(); i++ ) {
                        JSONObject jo = (JSONObject) ja.get(i);


                        int id = jo.getInt("id");
                        String name = jo.getString("name");

                    }

                }


            }
            catch (Exception e) {
                Toast.LENGTH_SHORT).show();
                return "Interrupted";

            }
于 2012-08-19T12:33:09.447 回答