【发布时间】:2011-03-02 00:19:26
【问题描述】:
我无法让简单 JSONObject 的 android POST 显示在服务器上的 $_POST 数据中。服务器是 PHP 5.3.4,android 端是 SDK 8 模拟器。我可以像往常一样发布一个简单的 NameValuePair,它会显示出来,但是当我切换到您在 $_POST 数组下方看到的 JSONObject + StringEntity 时,它会显示 {}。继续并针对我的测试 php 页面运行下面的代码。它具有 $_POST 和 $_SERVER 的 var_dump 以及搜索预期密钥之一(“电子邮件”)。你会看到我已经尝试了很多'ContentType'来看看这是否是问题所在。我什至使用 WireShark 来验证客户端和服务器之间的 TCP 对话是否正常。 POST 数据在那里,但它没有显示在服务器的变量中。我被困住了...感谢您提供的任何帮助。
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONObject;
import android.util.Log;
public class TestPOST {
protected static void sendJson (final String email, final String pwd) {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
String URL = "http://web-billings.com/testPost.php";
try{
HttpPost post = new HttpPost(URL);
// NameValuePair That is working fine...
//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//nameValuePairs.add(new BasicNameValuePair("email", email));
//nameValuePairs.add(new BasicNameValuePair("password", pwd));
//post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Log.i("main", "P2DB - String entity 'se' = "+nameValuePairs.toString());
JSONObject jObject = new JSONObject();
jObject.put("email", email);
jObject.put("password", pwd);
StringEntity se = new StringEntity(jObject.toString());
//se.setContentType("charset=UTF-8");
se.setContentType("application/json;charset=UTF-8");
//se.setContentType("application/json");
//se.setContentType("application/x-www-form-urlencoded");
post.setEntity(se);
Log.i("main", "TestPOST - String entity 'se' = "+GetInvoices.convertStreamToString(se.getContent()));
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
String message = GetInvoices.convertStreamToString(in);
Log.i("main", "P2DB - Connect response = "+message);
}
}
catch(Exception e){
e.printStackTrace();
//createDialog("Error", "Cannot Establish Connection");
}
}
}
如果你喜欢,这里是 testPost.php 页面:
<?php
echo "\r\n<pre>\r\n";
var_dump("\$_POST = ", $_POST)."\r\n";
echo '$_POST[\'email\'] = '.$_POST['email']."\r\n";
var_dump("\$_SERVER = ", $_SERVER)."\r\n";
echo '</pre>';
die;
?>
【问题讨论】: