2015-08-31 261 views
0

我是新來的Android的發展,我需要發送一個非常基本的HTTP POST請求到PHP服務器,以及跨越這個方法來:發送POST請求的Android

protected void performRequest(String name, String pn) { 
    String POST_PARAMS = "name=" + name + "&phone_number=" + pn; 
    URL obj = null; 
    HttpURLConnection con = null; 
    try { 
     obj = new URL("theURL"); 
     con = (HttpURLConnection) obj.openConnection(); 
     con.setRequestMethod("POST"); 

     // For POST only - BEGIN 
     con.setDoOutput(true); 
     OutputStream os = con.getOutputStream(); 
     os.write(POST_PARAMS.getBytes()); 
     os.flush(); 
     os.close(); 
     // For POST only - END 

     int responseCode = con.getResponseCode(); 
     Log.i(TAG, "POST Response Code :: " + responseCode); 

     if (responseCode == HttpURLConnection.HTTP_OK) { //success 
      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
      String inputLine; 
      StringBuffer response = new StringBuffer(); 

      while ((inputLine = in.readLine()) != null) { 
       response.append(inputLine); 
      } 
      in.close(); 

      // print result 
      Log.i(TAG, response.toString()); 
     } else { 
      Log.i(TAG, "POST request did not work."); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

但是當我運行這個應用程序崩潰,他說:

FATAL EXCEPTION: main 
Process: (the app id), PID: 11515 
android.os.NetworkOnMainThreadException 

雖然我明白,我需要在後臺線程執行這麼多,有沒有比較簡單的辦法做到這一點?

另外,我見過一種使用HttpClient發送post請求的方法,但似乎不推薦使用。它仍然可用嗎?

在此先感謝!

+0

複製後。這裏有很多其他的帖子。您需要在Asynctask而不是UI線程上進行網絡呼叫。請查找它。 – Actiwitty

+1

你會注意到這個問題的答案已經存在超過4年了。 – njzk2

回答

1

也許你正在在主線程的請求。我建議你使用像retrofit這樣的庫,它的請求更簡單。

+1

同意 - 改造(或其他類似的網絡庫)比嘗試重新發明車輪更可靠 –

0

你說得對,你需要在後臺任務中這樣做。最簡單的方法是使用AsyncTask。這裏是如何做到這一點的快速模板:

private class PostTask extends AsyncTask<Void, Void, HttpResponse> { 

    String POST_PARAMS; 
    Activity activity; 
    public PostTask(Activity activity, String params) {this.POST_PARAMS = params, this.activity = activity} 

    protected Long doInBackground(Void... params) { 
     HttpPost httpPost = new HttpPost("theURL"); 
     httpPost.setEntity(new StringEntity(POST_PARAMS)); 
     HttpResponse response; 
     response = client.execute(httpPost); 

    } 

    protected void onPostExecute(HttpResponse response) { 
     // Parse the response here, note that this.activity will hold the activity passed to it 
    } 
} 

每當你想運行它,只需調用new PostTask(getActivity(),PARAMS).execute()

+0

好的,我如何獲得對主線程的響應並使用它? – Mitt

+0

您應該在'onPostExecute'中執行所需的計算,因爲它在UI線程中運行 – asiviero

+0

但它在不同的類中(?)我如何獲得對活動的響應? (對不起,如果我聽起來啞巴,我真的不明白在Android開發中) – Mitt