2017-05-02 14 views
-5

我已經編寫了一個來自android應用程序的POST請求代碼,該應用程序將在服務器上運行一個php文件。如何從PHP獲取POST請求的答覆

String url = "http://****/****/Servlets.php"; 

    RequestQueue MyRequestQueue = Volley.newRequestQueue(this); 
    StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>(){ 
     @Override 
     public void onResponse(String response){ 
      //code when server responds 
     } 
    },new Response.ErrorListener(){ 
     @Override 
     public void onErrorResponse(VolleyError error){ 
      //Code if error is there 
      int test2 = 1; 
     } 
    }){ 
     protected Map<String, String> getParams() { 
      Map<String, String> MyData = new HashMap<String, String>(); 
      MyData.put("key",st); 
      return MyData; 
     } 
    }; 
    MyRequestQueue.add(MyStringRequest); 

Php文件的代碼正在調用一個java文件並獲取一些字符串值。如何將該字符串值返回給可以傳遞給onresponse()參數的android設備?還有等待迴應,或者我們該如何處理?

請建議。

+1

爲什麼在這裏雙斜槓。 '**** **** // //'? – Jens

+0

有沒有辦法捕捉異常?如果你會建議我發佈一個錯誤的方法 –

+0

有一個public void onErrorResponse(VolleyError error){'所以在那裏打印volleyerror,看看響應是什麼 – Denny

回答

1

嘗試使用此代碼,而不是你要的方式:

public String performPostCall(String requestURL, HashMap<String, String> postDataParams) { 
    URL url; 
    String response = ""; 
    try { 
     url = new URL(requestURL); 

     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setReadTimeout(15000); 
     conn.setConnectTimeout(15000); 
     conn.setRequestMethod("POST"); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 


     OutputStream os = conn.getOutputStream(); 
     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 
     writer.write(getPostDataString(postDataParams)); 

     writer.flush(); 
     writer.close(); 
     os.close(); 
     int responseCode = conn.getResponseCode(); 

     if (responseCode == HttpsURLConnection.HTTP_OK) { 
      String line; 
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      while ((line = br.readLine()) != null) { 
       response += line; 
      } 
     } else { 
      response = ""; 

     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return response; 
} 

然後你就可以通過編寫代碼得到的結果:

HashMap<String, String> params = new HashMap<String, String>(); 
    postDataparams.put("key", value); 
String response = performPostCall("url", postDataParams); 

這樣你就可以得到響應你的服務器。在服務器端,只需輸入echo即可發送到設備。沒有別的事情需要去做。這個異步線程將等待,直到它從服務器獲得響應。

希望這會有所幫助。

+0

只需在我的PHP端回顯「你好」會起作用嗎?還是我必須寫更多東西來處理迴應? –

+0

回聲「迴應」;將以響應的形式發回字符串。 –

+0

它工作完美,簡單易行。感謝學習者。 –