我正在尝试通过Android应用程序将数据发送到BufferedWriter
的PHP服务器。
在PHP方面,没有显示任何内容。我从PHP服务器接收数据,但问题是我发送数据的时候。
这是Java代码:
public class JsonTaskPost extends AsyncTask<String, String, String>
{
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params)
{
HttpURLConnection connection = null;
BufferedReader reader = null;
BufferedWriter writer = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
//connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
//connection.setRequestProperty("Accept", "application/json");
connection.setRequestMethod("POST");
forum_name = getIntent().getStringExtra(EXTRA_MESSAGE);
String data = URLEncoder.encode("forum_name", "UTF-8") + "=" + URLEncoder.encode(forum_name, "UTF-8");
//JSONObject data = new JSONObject();
//data.put("forum_name",forum_name);
OutputStream outStream = connection.getOutputStream();
writer= new BufferedWriter(new OutputStreamWriter(outStream));
writer.write(data);
connection.connect();
InputStream inStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
}
//catch (org.json.JSONException e){
// e.printStackTrace();
//}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally
{
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
if (writer != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
}
}
PHP代码已简化为几行:
<?php
include_once("config2.php");
include_once("connect.php");
echo($_POST);
?>
连接正常,因为我收到了数据。我在android logcat中收到的响应是:
注意:第6行的C:\ xampp \ htdocs \ phpBB \ android_api \ fetch_topics.php中的数组到字符串转换
我得到一个空数组。我也尝试过以JSON格式发送数据。