2016-05-13 102 views
1

我需要發送一個JSON POST從Android到Web服務器與PHP。我嘗試了很多代碼,但不起作用。錯誤404當收到POST

現在我嘗試一個簡單的POST與郵遞員,有和沒有發送數據。並總是收到404錯誤。如果我用GET發送數據,頁面工作正常。

看到了PHP,因爲如果你想測試:

網站:http://gclimb.com/Androidphp/index.php

<?php 
$json = file_get_contents('php://input'); 
$obj = json_decode($json); 
echo $obj["username"]; 
echo $obj["pass"]; 

if ($_POST["username"]) { 
echo $_POST["username"]; 
} 
if ($_GET["username"]) { 
echo $_GET["username"]; 
} 

?> 

編輯

POSTMAN screen

404錯誤:

POST /androidphp/index.php HTTP/1.1主機:gclimb.com緩存控制:no-cache郵遞員令牌:de575030-0343-64d9-fce3-e640ce12780c內容類型:multipart/form-data;邊界= ---- ---- WebKitFormBoundary7MA4YWxkTrZu0gW獲得404錯誤

做工精細:

GET /androidphp/index.php HTTP/1.1 主持人:gclimb.com 緩存控制:無緩存 郵差令牌:f2999796-9338-6ef6-9877-075be9a8e530

+0

對我來說postman的回報總是正確的......無論是在POST和GET。 – RaV

+0

用$ obj - > username替換$ obj [「username」]並重試。 –

+0

@RaV,真的嗎?我只選擇POST類型,並添加網址,並返回404錯誤-_-'相同:gclimb.com/androidphp/index.php?username=Myname(POST類型) – Cofeina

回答

0

在這裏,我將提供一個完整的PHP和Android應用程序從Android應用程序將數據發送到服務器。

假設你在你的數據庫有此表:

------------------------ 
| movie_id | movie_name| 
------------------------ 

1 PHP腳本

<?php 
$servername="localhost"; 
$username="root"; 
$password=""; 
$db="derar"; 
$connection=mysqli_connect($servername,$username,$password,$db); 
$json = file_get_contents('php://input'); 
$obj = json_decode($json,true); 
$movie_name=$obj['movie_name']; 
mysqli_query($connection,"insert into movie (movie_id, movie_name) VALUES (NULL,'$movie_name');"); 
echo "inserted"; 
?> 

這個代碼是簡單的代碼,你必須把SQL注入。

2- Android應用程序

activity_main。XML

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.example.win7.derar.MainActivity"> 

    <Button 
     android:id="@+id/send_button" 
     android:layout_width="match_parent" 
     android:text="إضغط لإرسال المعلومات" 
     android:layout_height="wrap_content" /> 
</RelativeLayout> 

MainActivity

public class MainActivity extends AppCompatActivity { 
    private Button send_button; 
    private String Server_URL="http://192.168.1.101/derar/insertDataToServer.php"; 
    private String movie_name="Titanic"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     send_button=(Button)findViewById(R.id.send_button);// Button Assignment 
     send_button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       SendDataToServer sendDataToServer=new SendDataToServer(); 
       sendDataToServer.execute(Server_URL,movie_name); 


      } 
     });// Button On Click Listener 
    } 


    private class SendDataToServer extends AsyncTask<String, Void, Boolean> { 

     @Override 
     protected Boolean doInBackground(String... urls) { 

      OutputStream os = null; 
      InputStream is = null; 
      HttpURLConnection conn = null; 


      try { 

       URL url = new URL(urls[0]); 
       JSONObject jsonObject = new JSONObject(); 
       jsonObject.put("movie_name", urls[1]); 
       String message = jsonObject.toString(); 
       Log.d(message, "Test"); 
       conn = (HttpURLConnection) url.openConnection(); 
       conn.setReadTimeout(10000); 
       conn.setConnectTimeout(15000); 
       conn.setRequestMethod("POST"); 
       conn.setDoInput(true); 
       conn.setDoOutput(true); 
       conn.setFixedLengthStreamingMode(message.getBytes().length); 

       conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); 
       conn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); 

       conn.connect(); 

       os = new BufferedOutputStream(conn.getOutputStream()); 
       os.write(message.getBytes()); 

       os.flush(); 

       is = conn.getInputStream(); 


      } catch (MalformedURLException e) { 
       Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); 
       ; 
       e.printStackTrace(); 
       return false; 
      } catch (IOException e) { 
       Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); 
       ; 
       e.printStackTrace(); 
       return false; 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } finally { 

       try { 
        assert os != null; 
        os.close(); 
        assert is != null; 
        is.close(); 

       } catch (IOException e) { 

        e.printStackTrace(); 
       } 

       conn.disconnect(); 
      } 


      return true; 
     } 


     @Override 
     protected void onPostExecute(Boolean result) { 
      if (result) { 


        Toast.makeText(getApplicationContext(), "لقد نجح إرسال المعلومات", Toast.LENGTH_LONG).show(); 
      } else { 
       Toast.makeText(getApplicationContext(), "فشل في إرسال المعلومات", Toast.LENGTH_LONG).show(); 

      } 

     } 
    } 
} 

而且不要忘記這樣做:

1添加此權限清單文件:

<uses-permission android:name="android.permission.INTERNET" /> 

2-更改來自的IP地址

到您自己的IP地址,以運行本地主機服務器。

我希望這對你有用。

+0

很多感謝@SubhiMMM!完美的工作。你如何獲得PHP的迴應? (「回聲」插入「;」)。 – Cofeina

+0

請提供更多詳情(如何獲得php響應?)。 – SubhiMMM

0

當進行POST request,不要忘了,請求路徑是區分大小寫

試用執行與這一目標你的要求:

http://gclimb.com/androidphp/index.php