在HTTPURLConnection上进行POST的简单方法? [英] easy way to do POST on HTTPURLConnection?

查看:110
本文介绍了在HTTPURLConnection上进行POST的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android的AsyncTask中对HTTPURLCONNECTION进行POST的最简单方法是什么? 我只想将数据发布到我的php文件中,然后将返回一个json响应

what is the easiest way to do POST on HTTPURLCONNECTION in AsyncTask on android? I just want to post data on my php file which will then return me a json response

推荐答案

您可以从前几天我给您的答案中得到答案: 如何使用HttpURLConnection来获取JSON对象凌空?

You can piece it together from this answer I gave you the other day: How to get JSON object using HttpURLConnection instead of Volley?

...以及此处的答案: Java -通过POST方法轻松发送HTTP参数

... and the answer here: Java - sending HTTP parameters via POST method easily

话虽这么说,开始发送POST数据并获得JSON结果的最简单方法是只使用旧的API.

That being said, the easiest way to get started sending POST data and getting a JSON result is to just use the old APIs.

这是一个可行的示例:

class CreateNewProduct extends AsyncTask<String, String, JSONObject> {

        InputStream is = null;
        JSONObject jObj = null;
        String json = "";

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ShareNewMessage.this);
            pDialog.setMessage("Sharing Message...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected JSONObject doInBackground(String... args) {

            String message = inputMessage.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", username));
            params.add(new BasicNameValuePair("message", message));

            Log.d("Share", "Sharing message, username: " + username + " message: " + message);

            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url_create_message);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Share", "Error converting InputStream result " + e.toString());
            }

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("Share", "Error parsing JSON data " + e.toString());
            }

            try{
                int success = jObj.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product

                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return jObj;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(JSONObject jObj) {

            //do something with jObj

            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }

这篇关于在HTTPURLConnection上进行POST的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆