2

I want to send data to server with Authentication header with some data in body.

i tried with this code

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

and i am getting this Exception

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

And i need to send Data like this

enter image description here

And in return i will get the following response

enter image description here

Please help if anyone of you know how i can achieve this. Thanks

Mustanser Iqbal
  • 5,017
  • 4
  • 18
  • 36

3 Answers3

4

Because your response is a JSONObject, you can refer to my following sample code:

        // 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();
        }

About Volley, you can read more from the following

Transmitting Network Data Using Volley

Hope this helps!

BNK
  • 23,994
  • 8
  • 77
  • 87
  • i'll give it a try after sometime then i'll let you know – Mustanser Iqbal Oct 31 '15 at 09:39
  • Another source for Volley is https://github.com/mcxiaoke/android-volley/blob/master/README.md – BNK Oct 31 '15 at 09:40
  • 1
    Maann you are awesome. that did the trick for me. seriously you saved my life.. though i was trying with different method like httprequest, httpost, and bla bla.... but when i move towards volley then it works like a charm. Thanks @BNK. – Mustanser Iqbal Nov 02 '15 at 05:48
  • 1
    You're welcome, glad my answer could help, happy coding :) – BNK Nov 02 '15 at 06:09
  • BNK can you please tell me how can i send Delete Request using Volley with headers and parameters? – Mustanser Iqbal Nov 05 '15 at 13:18
  • Pls wait until tomorrow. I have no testing environment now. – BNK Nov 05 '15 at 14:19
  • You can read the following and try before http://stackoverflow.com/questions/16626032/volley-post-get-parameters and http://stackoverflow.com/questions/22803766/volley-how-to-send-delete-request-parameters and http://stackoverflow.com/questions/28201328/send-a-delete-request-using-volley-android-to-a-rest-api-with-parameters – BNK Nov 05 '15 at 14:26
  • i checked these posts already i'll post my new question.. i have tried some code but i always get bad request error. i'll post as well then please let me know what m doing wrong – Mustanser Iqbal Nov 05 '15 at 14:50
  • Ok, I will read your new question tomorrow morning, must go to sleep now, goodnight and goodluck :) – BNK Nov 05 '15 at 14:53
  • i tried alot but no sucess please check my new question and please help me if you can help i'll be very thankful to you http://stackoverflow.com/q/33553559/3593066 – Mustanser Iqbal Nov 05 '15 at 19:53
0

If you want to pass the data, then you need to use name value pair concept of httppost available for android.
Try following code, it may help your

// 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,765
  • 8
  • 41
  • 56
  • No its not the name value pair data... this data is in being sent in body instead of key values... do you have any idea how i can send data in body @Ichigo Kurosaki – Mustanser Iqbal Oct 31 '15 at 08:33
0

Try adopting the following code..

   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

See to that you are adding Base64.NO_WRAP param. Without it, the code may not work.Using HTTP basic authentication is unsafe hence you might try oAuth as well..