[英]How to display android POST string on PHP server?
我試圖從我的Android應用程序發送json字符串到我的PHP服務器。 下面是我的mobiledb_control.php和httpconnect.java的完整代碼
Log.v(“HTTPSENDER”,“工作”); 運行,我沒有錯誤。 但是我的error_log(“in”); 不運行。
如何將通過android發送的JSON顯示到我的error_log()中?
HttpConnect.java:
public class HttpConnect {
public HttpConnect(){
}
public void sendData(String jsonObject){
try{
URL url = new URL("http://www.alextanti.net/PHPDashboard/Backend/mobiledb_control.php");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
output.write("json="+jsonObject);
output.flush();
output.close();
Log.v("HTTPSENDER","WORKED");
}catch(Exception e){
e.printStackTrace();
}
}
}
mobiledb_control.php:
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set("error_log", "../Logs/error.log");
error_reporting(E_ALL);
if(!empty($_POST['json'])){
echo(var_dump($_POST['json']));
error_log($_POST['json']);
}
$headers = apache_request_headers();
?>
在PHP代碼中嘗試這個
並打開這樣的錯誤報告
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
和
print_r($_POST);
為了更清楚地說明你從帖子中獲得了什么。
使用php的編碼和解碼函數來制作和解析json。
$request=json_decode($_POST['json']); // it gives the Array foreach($request as $values){ echo($values['your_value1']) echo($values['your_value2']) }
在設計服務器 - 客戶端通信時,必須確保客戶端和服務器可以相互通信。 考慮到這一點,您可以通過在try塊中的代碼中添加它來提供服務器響應代碼:
try {
...
Log.d(TAG, "code: " + conn.getReturnCode());
InputStream is = conn.getInputStream();
String serverReply = readIt(is, 500);
Log.d(TAG, serverReply);
...
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
它將分別返回200和401。 如果無法從響應中識別代碼,則返回-1(即,響應不是有效的HTTP)。
干杯!
似乎修復了它,但我不知道如何
PHP文件:
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set("error_log", "../Logs/location.log");
error_reporting(E_ALL);
if(!empty($_POST['json'])){
echo(var_dump($_POST['json']));
error_log($_POST['json']);
}
?>
JAVA文件:
public class HttpConnect {
public HttpConnect(){
}
public void sendData(String jsonObject){
try{
URL url = new URL("http://www.alextanti.net/PHPDashboard/Backend/mobiledb_control.php");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
output.write("json="+jsonObject);
output.flush();
output.close();
Log.v("HTTPSENDER","WORKED");
Log.v("HTTPSENDER",""+conn.getResponseCode());
}catch(Exception e){
e.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.