我正在将JSON对象从我的Android应用程序发送到我的服务器。在我开发的本地机器中,它运行良好。我获取数据并对其进行解码。但当我将服务器部署到计算引擎时,我不会在服务器端接收到数据。数据是从Android客户端发送的。我还测试了浏览器中的JSON,得到了200个响应代码。以下是代码片段:
//客户端
//在此处创建JSONObject这是我正在发送的JSON{"test","1234"}
JSONObject json = new JSONObject();
json.put("test", args[0]);
String postData=json.toString();
// Send POST output.
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.e("NOTIFICATION", "Sent");
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg="";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line;
}
Log.i("msg=",""+msg);
//服务器
<?php
$json = file_get_contents("php://input");
var_dump($json); //this returns String(0)
$decoded = json_decode($json, TRUE);
$pasid = $decoded['test'];
echo"test if it works";
var_dump($pasid); //returns null
无论我做什么,Android应用程序都会发送一个字符串,但在服务器端,我得到的是空字符串。到目前为止我不明白为什么。
您的代码非常混乱这不是将数据从应用程序发送到远程数据库的好方法你可以这样做`
形成应用
String uri="But your http URL";
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStreamWriter writer=new OutputStreamWriter(con.getOutputStream());
StringBuilder sb=new StringBuilder();
sb.append("username="+"Naham");
sb.append("password="+"passNaham");
writer.write(sb.toString());
writer.flush();
了解简单的php web服务
$data=array("result"=>0,"message"=>"Error!");if($_SERVER['REQUEST_METHOD']=="POST"){$user_name=isset($_POST['username])$_POST['user_name']:";$user_password=isset($_POST['user_password'])$_POST['user_password']:";//在这里做点什么$data=array("result"=>1,"message"=>"welcome");}其他$data=array("result"=>0,"message"=>"Error!");/*输出标题*/header('Content-type:application/json');echo json_encode($data);?>
在向服务器发送帖子请求后,您可以使用以下代码获得帖子正文:
<?php
$post_body = file_get_contents("php://input");
$json = json_decode($post_body);
$pasid = $json->{"test"};
echo $pasid;
?>
发现问题是由HttpRLConnection引起的。就像这个SO问题中被接受的答案一样,只需删除`
urlConnection.setChunkedStreamingMode(0);
其中`urlConnection=HttpUrlCooenction();
`