【问题标题】:Add body in Post Request with Authentication Header android使用身份验证标头android在发布请求中添加正文
【发布时间】:2015-10-31 06:55:00
【问题描述】:

我想将数据发送到带有身份验证标头的服务器,其中包含一些数据。

我用这段代码试过了

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 之类的数据

作为回报,我会得到以下回复

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

【问题讨论】:

    标签: java android http-post httpresponse


    【解决方案1】:

    因为你的响应是一个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

    希望这会有所帮助!

    【讨论】:

    • 过一段时间我会试一试,然后我会告诉你的
    • 马恩你太棒了。这对我有用。说真的,你救了我的命.. 虽然我尝试了不同的方法,如 httprequest、httpost 和 bla bla....但是当我转向 volley 时,它就像一个魅力。谢谢@BNK。
    • 不客气,很高兴我的回答对您有帮助,祝您编码愉快 :)
    • BNK 你能告诉我如何使用带有标题和参数的 Volley 发送删除请求吗?
    【解决方案2】:

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

    // 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
    }
    

    【讨论】:

    • 不,它不是名称值对数据...此数据是在正文而不是键值中发送的...您知道我如何在正文中发送数据@Ichigo Kurosaki
    【解决方案3】:

    尝试采用以下代码..

       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 参数。没有它,代码可能无法工作。使用 HTTP 基本身份验证是不安全的,因此您也可以尝试 oAuth..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 2013-11-26
      • 2020-05-06
      • 2018-07-30
      • 2018-11-29
      • 1970-01-01
      • 2020-03-24
      相关资源
      最近更新 更多