我想向 PHP 服务器发送一个简单的 JSON 对象,但是当我尝试在服务器端检索该对象时,没有任何内容,我的意思是我的 $_POST 变量为空。服务器端是 PHP 5.2,我正在使用 android 模拟器 10 ...有人可以看看我的代码并告诉我出了什么问题吗? 非常感谢
public void uploadJSon() throws ClientProtocolException, IOException, JSONException{
HttpClient httpclient = new DefaultHttpClient();
String url = "http://so-dev-deb.niv2.com/suivi_activite/test.php";
HttpPost httppost = new HttpPost(url);
JSONObject json = new JSONObject();
json.put("username", "bob");
json.put("email", "test@testsite.com");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("value", json.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
URL test_url = new URL(url);
URLConnection connection = test_url.openConnection();
connection.setDoOutput(true);
HttpResponse response;
response = httpclient.execute(httppost);
Log.i("NVPS",nvps.get(0).toString());
Log.i("JSON",json.toString());
Log.i("response", response.getEntity().getContent().toString());
Log.i("response status",response.getStatusLine().toString());
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
//System.out.println(decodedString);
Log.i("info 10",decodedString);
}
in.close();
}
服务器端 test.php 是:
<?php
$tmp = json_decode($_POST['value']);
var_dump($tmp);
?>
最佳答案
我通常采用这种方法在 Java 代码中生成 JSON 对象:
StringWriter writer = new StringWriter();
JSONWriter jsonWriter = new JSONWriter(writer);
jsonWriter.object();
jsonWriter.key("key1").value("test1");
jsonWriter.key("key2").value("test2");
jsonWriter.endObject();
String toSend = writer.toString();
关于java - 如何将 JSONObject 从 Android 应用程序传递到 PHP 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6203083/