【发布时间】:2013-04-05 13:23:24
【问题描述】:
我正在尝试将 Android 应用程序连接到 java webservice 以获取 pHp 解析值。
PHP 脚本是:
<?php
$data = array('name' => 'Froyo', 'version' => 'Android 2.2');
print (json_encode($data));
?>
Java WebService 是:
package com.json.php;
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 android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONExampleActivity 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://127.0.0.1/test.php");
TextView textView = (TextView)findViewById(R.id.textView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
String name = object.getString("name");
String verion = object.getString("version");
textView.setText(name + " - " + verion);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
我在 HttpPost 中同时尝试了 http://127.0.0.1/test.php and http://localhost/test.php,它不起作用。
我在浏览器上检查了我的 php 文件,结果很好。
我哪里错了?
另外我正在使用Mac,由于所有权限问题,这是否与问题有关?
【问题讨论】:
-
你在模拟器上吗?
-
@silentw 是的,我在模拟器上
-
尝试使用
10.0.2.2而不是 127.0.0.1。如果您使用的是 MAMP,可能需要将端口添加到 ip(默认为10.0.2.2:8888) -
@silentw 10.0.2.2 工作!非常感谢!
-
@Arihant 如果您找到了答案,请接受它
标签: php android json localhost