我正在尝试从一个简单的Android应用发送消息并将其保存在服务器中。
这是服务器
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Title...
</title>
</head>
<body>
<section style="text-align:center;">
<?php
$data = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
ob_start();
var_dump($_POST['data']);
$message = ob_get_contents();
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $message);
fclose($handle);
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
message: <br/>
<input type="text" name="data" value="<?php echo $data;?>"><br/>
<input type="submit" name="submit" value="Submit">
</form>
</section>
</body>
</html>
该应用与https://developer.android.com/training/basics/firstapp/starting-activity中的第一个应用相同,另外还提供了互联网许可和一些用于发送消息的代码
公共类DisplayMessageActivity扩展了AppCompatActivity {
private static final String myURL = "https://[mywebsite].000webhostapp.com/index.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView textView = findViewById(R.id.textView);
textView.setText(message);
URL url;
StringBuilder sb = new StringBuilder();
try {
url = new URL(myURL);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput( true );
conn.setDoInput( true );
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
HashMap<String, String> params = new HashMap<>();
params.put("data", message);
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
while ((response = br.readLine()) != null) {
sb.append(response);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
页面本身可以创建预期的文件,但该应用程序无法创建,我编写了消息,按send键,它显示了带有消息的显示屏,没有任何其他错误或异常。我在做什么错了?
编辑:网络部分必须在另一个线程中完成
protected void onCreate(Bundle savedInstanceState) {
...
textView.setText(message);
callAsyncTask();
}
private void callAsyncTask() {
class ATaskCaller extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
...
[network stuff]
...
}
}
ATaskCaller atc = new ATaskCaller();
atc.execute();
}
答案 0 :(得分:-1)
确保您的服务器接受cors。
您正在尝试发布信息,因此您的服务器应该接受它。响应标头应包含:
访问控制允许方法:POST
访问控制允许来源:*
https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Controle_Acesso_CORS