在Android中发送POST请求

时间:2015-08-31 18:13:55

标签: android multithreading post httpurlconnection

我是Android开发的新手,我需要向PHP服务器发送一个非常基本的HTTP POST请求,并且遇到了这种方法:

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发送帖子请求的方法,但它似乎已被弃用了。它仍然可以使用吗?

提前致谢!

3 个答案:

答案 0 :(得分:1)

可能你是在主线程中提出请求。我建议您使用像retrofit这样的库来完成更简单的请求。

答案 1 :(得分:0)

您应该使用AsyncTask类。 Android根本不允许用户在主线程上执行长时间运行的网络操作。这将阻止线程。因此不允许程序正常运行。  这里有一些参考。 http://developer.android.com/reference/android/os/AsyncTask.html

http://www.youtube.com/watch?v=B25Nx48JuVo

答案 2 :(得分: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()

相关问题