使用BasicAuth POST https请求的参数

时间:2015-03-19 18:03:56

标签: android http http-headers httprequest httpresponse

我遇到了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);

1 个答案:

答案 0 :(得分:0)

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);

        }