我想从Android应用程序访问一个简单的php Web服务。为了测试这个,我用json编码创建了这个第一个php web服务,并将它托管在本地主机上运行的WAMPSERVER中。
<?php
$string='{"name":"John Adams"}';
echo json_encode($string);
?>
要访问此网络服务,我创建了一个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();}
}
}
我添加了互联网权限,但这只是空白屏幕。我知道这个问题非常简单,但我无法解决。请帮助,错误是什么以及我如何纠正这个错误。
提前致谢!
答案 0 :(得分: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";
}