使用 BasicAuth 的 POST https 请求的参数

parameters to POST https request with BasicAuth

我受困于 POST 对服务器的 http 请求。此请求具有我已成功通过的凭据(基本身份验证)。

但我不知道如何将 BasicNameValuePair 传递给这样的请求。

那是我试过的:

// Create a new HttpClient and Post Header
String downloadedString = null;

HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
HttpPost httppost = new HttpPost(host);

//add data
List<NameValuePair> nameValuePairs = new ArrayList<>(3);

nameValuePairs.add(new BasicNameValuePair("email", params[0]));
nameValuePairs.add(new BasicNameValuePair("password", params[1]));
nameValuePairs.add(new BasicNameValuePair("new_password", params[2]));

//passing credentials
HttpUriRequest request = new HttpPost(host);
String credentials = Global.getSharedPreferences(activity, Global.KEY_EMAIL) + ":" + Global.getSharedPreferences(activity, Global.KEY_PASS);
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.addHeader("Authorization", "Basic " + base64EncodedCredentials);

//executing request
response = httpclient.execute(request);

//parsing response to string
InputStream in = response.getEntity().getContent();
StringBuilder stringbuilder = new StringBuilder();
BufferedReader bfrd = new BufferedReader(new InputStreamReader(in), 1024);
String line;
while ((line = bfrd.readLine()) != null) {
    stringbuilder.append(line);
        }
 //result
downloadedString = stringbuilder.toString();

所以问题我如何将那些nameValuePairs传递给服务器请求??

P.S。 没有凭据我是这样做的:

//add data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

Volley 库让这一切变得简单多了。您可以使用 volley 来试试这个。

private void postMethod(final String url,final String userName, final String password) {

            RequestQueue rq = Volley.newRequestQueue(getActivity());
            StringRequest postReq = new StringRequest(Request.Method.POST,url,
    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response1) {
                        // your response will be received here  

                        }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    System.out.println("Error [" + error + "]");

                }
            }) {

                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();

                    params.put("username","myname");
                    params.put("password","mypassword");

                    return params;
                }

            };

            rq.add(postReq);

        }