2015-08-31 180 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