在 Post 中添加 body 带有身份验证的请求 Header android

Add body in Post Request with Authentication Header android

我想通过身份验证 header 将数据发送到服务器 body 中的一些数据。

我试过这个代码

HttpPost request;
HttpParams httpParameters;

httpParameters = new BasicHttpParams();

request = new HttpPost(url);

String auth = android.util.Base64.encodeToString((mUserSession.getUserEmail() + ":" + mUserSession.getUserPassword()).getBytes("UTF-8"),android.util.Base64.DEFAULT);

request.addHeader("Authorization", "Basic " + auth);

httpParameters.setParameter("nombre",String.valueOf(params.get("nombre")));
httpParameters.setParameter("annee",String.valueOf(params.get("annee")));
httpParameters.setParameter("photo",String.valueOf(params.get("photo")));
HttpConnectionParams.setSoTimeout(httpParameters, 1000);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse response = client.execute(request);
String userAuth = EntityUtils.toString(response.getEntity());
int statusCode = response.getStatusLine().getStatusCode();
request = new HttpPost(url);
HttpEntity entity = response.getEntity();
if (entity != null) {
        entity.consumeContent();
}
String cookiesString = null;
List<Cookie> cookies = client.getCookieStore().getCookies();
if (!cookies.isEmpty()) {
Log.e("cookies Length ", "cookies Length = " + cookies.size());
for (int i = 0; i < cookies.size(); i++) {
        cookiesString = cookies.get(i).getValue();
     }
}
Log.e("userAuth", "user auth= " + userAuth);

我得到了这个异常

10-31 10:36:39.272: D/dalvikvm(6354): GC_FOR_ALLOC freed 4K, 46% free 35542K/65172K, paused 21ms, total 21ms
10-31 10:43:08.222: E/cookies Length(6590): cookies Length = 1
10-31 10:43:08.222: E/userAuth(6590): user auth= <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
10-31 10:43:08.222: E/userAuth(6590): <title>400 Bad Request</title>
10-31 10:43:08.222: E/userAuth(6590): <h1>Bad Request</h1>
10-31 10:43:08.222: E/userAuth(6590): <p>The browser (or proxy) sent a request that this server could not understand.</p>
10-31 10:43:08.222: E/statusCode(6590): statusCode = 400
10-31 10:43:08.222: E/cookiesString(6590): cookies String = eyJfaWQiOiJmNmJhZGJhNTk2ODM4ODJjMDczMWE5ZTZhNWU0M2EyMyJ9.CRXmqA.yJ67mWRqEPQ-aYk7l-7yP_0Gzxg

我需要发送数据,例如 this

并且在 return 中我将得到 以下响应

如果你们中有人知道我如何实现这一点,请提供帮助。谢谢

如果要传递数据,则需要使用android可用的httppost的名称值对概念。
试试下面的代码,它可能对您有帮助

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

因为你的响应是一个JSONObject,你可以参考我下面的示例代码:

        // HTTP POST
        String url = "http://...";
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("key1", "value1");
            jsonObject.put("key2", "value2");
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    // do something...
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // do something...
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    final Map<String, String> headers = new HashMap<>();
                    headers.put("Authorization", "Basic 5OoZd9uHbC9nNmIXqJTN_thbQc54kygD3FEqViMclaj8E1FfDKv8p...");
                    return headers;
                }
            };
            requestQueue.add(jsonObjectRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }

关于Volley,您可以从以下

阅读更多内容

Transmitting Network Data Using Volley

希望对您有所帮助!

尝试采用以下代码..

   HttpUriRequest request = new HttpGet(YOUR_URL); // Or HttpPost(), depends on your needs  
    String credentials = YOUR_USERNAME + ":" + YOUR_PASSWORD;  
    String auth = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);  
    request.addHeader("Authorization", "Basic " + auth);

    HttpClient httpclient = new DefaultHttpClient();  
    httpclient.execute(request);  
    //Handle Exceptions

确保您正在添加 Base64.NO_WRAP 参数。没有它,代码可能不会 work.Using HTTP 基本身份验证是不安全的,因此您也可以尝试 oAuth..