android发送http post请求 - 正确的方法

时间:2016-05-25 07:04:56

标签: android

早上好,

我找到了一个有用的教程,用于使用android发出HTTP POST请求。 这段代码工作正常,但我想知道,如果这段代码是最好的方法,或者如果你有任何想法,我怎么能优化它。

private class PostClass extends AsyncTask<String, String, String> {

        Context context;

        public PostClass(Context c){
            this.context = c;
        }


        @Override
        protected String doInBackground(String... params) {
            try {

                URL url = new URL("xxxx");

                HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                String urlParameters = "xxx";

                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
                dStream.writeBytes(urlParameters);
                dStream.flush();
                dStream.close();


                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                final String response =  br.readLine();
                br.close();

                return response;


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }




        protected void onPostExecute(String result){
            Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
        }

    }

3 个答案:

答案 0 :(得分:1)

根据同步频率,您可以使用Volley。此外,您还可以使用以下代码,以便在POST请求中发送多个参数

HttpClient httpclient = new DefaultHttpClient();
        String responseStr="";
        String URL=Constants.API_URL;#URL where request needs to be sent
        HttpPost httppost = new HttpPost(URL);

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("id", pick_up_id));
            nameValuePairs.add(new BasicNameValuePair("driver_photo", strPhoto));#image in form of Base64 String which you need to send

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            int responseCode = response.getStatusLine().getStatusCode();
            switch(responseCode) {
            case 200:
                HttpEntity entity = response.getEntity();
                if(entity != null) {
                    String responseBody = EntityUtils.toString(entity);
                    responseStr=responseBody;
                }
                break;
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        System.out.println("this is response "+responseStr);

答案 1 :(得分:0)

以下是使用Volly library

的示例Http Post Request
      void MakePostRequest() {
            StringRequest postRequest = new StringRequest(Request.Method.POST, EndPoints.BASE_URL_ADS,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonResponse = new JSONObject(response);
                                value1= jsonResponse.getString("Your ID1");
                                value2= jsonResponse.getString("Your ID2");

                            } catch (JSONException e) {
                                e.printStackTrace();
                                banner_id = null;
                                full_id = null;
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            error.printStackTrace();
                            value1= null;
                            value2= null;
                        }
                    }
            ) {
           // here is params will add to your url using post method
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<>();
                    params.put("app", getString(R.string.app_name));
                    //params.put("2ndParamName","valueoF2ndParam");
                    return params;
                }
            };
            Volley.newRequestQueue(this).add(postRequest);
        }

此帖子请求正在使用此compile 'com.mcxiaoke.volley:library:1.0.19'排球版。

我只是添加应用名称作为参数。您可以添加更多参数。

答案 2 :(得分:0)

是的,这是正确的。我创建了一个类似于此内容的库来处理这样的请求:https://github.com/gjudkins/GjuddyRequest

将依赖项添加到build.gradle:

repositories {
  maven {
    url 'https://dl.bintray.com/gjudkins/maven'
  }
}

dependencies {
  compile 'com.gjuddy:easyhttprequest:0.1.17'
}

然后发出请求看起来像这样:

// define headers
ContentValues headers = new ContentValues();
bodyParams.put("FirstHeader","header-value");
bodyParams.put("AnotherHeader","add as many as you want");

// define parameters
ContentValues bodyParams = new ContentValues();
bodyParams.put("name","the_name");
bodyParams.put("another_param","add as many as you want");

// define how GjuddyRequest will format the body/parameters of the request
// !! The appropriate headers for the ContentType defined here are AUTOMATICALLY added to the request !!
GjuddyRequest.ContentType bodyFormat = GjuddyRequest.ContentType.x_www_url_form_urlencoded;

// make the POST request
GjuddyRequest.getInstance().makePostAsync("https://your.api.url", bodyParams, bodyFormat, headers, new GjuddyRequest.HttpRequestCallback() {
    @Override
    public void requestComplete(GjuddyResponse response) {
        // check for errors
        if (response.getErrors() == null) {
            // the GjuddyResponse object can automatically retrieve the response
            // as a String, JSONObject, or JSONArray
            JSONObject jsonResponse = response.toJSONObject();
            Log.e("GJUDDY", response.toString());
        } else {
            Log.e("GJUDDY", response.getErrorString());
        }
    }
});

链接中的GitHub自述文件深入探讨了如何使用它,但它非常简单。