我正在尝试从Android应用程序向php服务器发送JSON数据。我只是要求服务器打印原始数据,但它没有显示在网络上。我无法弄清楚可能是什么原因。 DisplayMessageActivity.java:
public class DisplayMessageActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
new SaveTheFeed().execute();
}
class SaveTheFeed extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MapsActivity.EXTRA_MESSAGE);
double longitude = intent.getDoubleExtra(MapsActivity.EXTRA_LONGITUDE, 0.0);
double latitude = intent.getDoubleExtra(MapsActivity.EXTRA_LATITUDE, 0.0);
// Create the JSONObject
JSONObject request = CreateRequest(message, longitude, latitude);
//JSONObject response = null;
URL url = null;
HttpURLConnection client = null;
try {
// Establish http connection
url = new URL("http://********.com/");
client = (HttpURLConnection) url.openConnection();
client.setDoOutput(true);
client.setDoInput(true);
client.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
client.setRequestMethod("POST");
client.connect();
Log.d("doInBackground(Request)", request.toString());
// Send the JSON object to the server
OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());
String output = request.toString();
writer.write(output);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.disconnect();
}
return null;
}
private JSONObject CreateRequest(String message, double longitude, double latitude) {
JSONObject request = new JSONObject();
try {
request.put("message", message);
request.put("longitude", longitude);
request.put("latitude", latitude);
} catch (JSONException e) {
e.printStackTrace();
}
return request;
}
}
}
php代码:
<!DOCTYPE html>
<html>
<body>
<h2>This is your current location :)
<?php
$json = file_get_contents('php://input');
$request = json_decode($json, true);
echo ($json);
?>
</h2>
<div id="map"></div>
</body>
</html>
答案 0 :(得分:0)
我认为您在代码中遗漏的是使用URLEncoder
对字符串进行编码。而不是只写原始字符串编写字符串之前写入它。尝试替换此行:
writer.write(output)
这一行
writer.write(URLEncoder.encode(output,"UTF-8");
让我知道输出。 您还可以参考stackoverflow中的this link
<强>更新强>
另外,不要忘记在logcat窗口中记录服务器响应。为此,只需添加以下代码行:
String line="";
BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=reader.readLine())!=null){
response+=line;
}
Log.d("response from server",response);
reader.close();