1

I am doing basic authentication by passing username and password and then using BasicNameValuePair for sending post params to get the response from the service.

My method:

public StringBuilder callServiceHttpPost(String userName, String password, String type)
    {

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(WEBSERVICE + type);



        HttpResponse response = null;

        StringBuilder total = new StringBuilder();

        try {

            URL url = new URL(WEBSERVICE + type);

            /*String base64EncodedCredentials = Base64.encodeToString((userName
                    + ":" + password).getBytes(), Base64.URL_SAFE
                    | Base64.NO_WRAP);*/

            String base64EncodedCredentials = "Basic " + Base64.encodeToString(
                    (userName + ":" + password).getBytes(),
                    Base64.NO_WRAP);


            httppost.setHeader("Authorization", base64EncodedCredentials);

            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("day", Integer.toString(2)));
            nameValuePairs.add(new BasicNameValuePair("emailId", "usertest@gmail.com"));
            nameValuePairs.add(new BasicNameValuePair("month", Integer.toString(5)));
            nameValuePairs.add(new BasicNameValuePair("year", Integer.toString(2013)));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

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

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            try {
                InputStream instream = entity.getContent();

                String line = "";


                // Wrap a BufferedReader around the InputStream
                BufferedReader rd = new BufferedReader(new InputStreamReader(instream));

                // Read response until the end
                while ((line = rd.readLine()) != null) { 
                    total.append(line); 
                }

            } catch (IllegalStateException e) {

                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }


        return total;
    }

But I am getting this in total:

 <html><head>   <title>Status page</title></head><body><h3>Invalid json representation of content</h3><p>You can get technical details <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1">here</a>.<br>Please continue your visit at our <a href="/">home page</a>.</p></body></html>
sjain
  • 23,126
  • 28
  • 107
  • 185

3 Answers3

6

This is how to do it:

public String callServiceHttpPost(String userName, String password, String type)
    {

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(WEBSERVICE + type);

            String responseBody = "";

        HttpResponse response = null;

        try {

            String base64EncodedCredentials = "Basic " + Base64.encodeToString( 
                    (userName + ":" + password).getBytes(), 
                    Base64.NO_WRAP);


            httppost.setHeader("Authorization", base64EncodedCredentials);

            httppost.setHeader(HTTP.CONTENT_TYPE,"application/json");

            JSONObject obj = new JSONObject();

            obj.put("day", String.valueOf(2)); 
            obj.put("emailId", "userTest@gmail.com");
            obj.put("month", String.valueOf(5));
            obj.put("year", String.valueOf(2013));


             httppost.setEntity(new StringEntity(obj.toString(), "UTF-8"));

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

            if (response.getStatusLine().getStatusCode() == 200) {
                 Log.d("response ok", "ok response :/");
            } else {
                Log.d("response not ok", "Something went wrong :/");
            }

            responseBody = EntityUtils.toString(response.getEntity());

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch (JSONException e) {
            e.printStackTrace();
        }

        return responseBody;
    }
sjain
  • 23,126
  • 28
  • 107
  • 185
1

It seems that content you are adding is not in JSON format.

Here is what I suggest:

  1. Prepare your content in Map<String, String>

    Map<String, String> inputMap = new HashMap<String, String>();  
    inputMap.put("day", String.valueOf(5));
    
  2. Transform it to JSON, for example with Gson (add gson to Maven or put to your assets folder):

    private static final Gson gson = new 
    GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
    

    and then transform prepared map with gson.toJson(inputMap).

  3. Resulting string containing the content in JSON format add to your httppost like this:

    BasicHttpEntity httpEntity = new BasicHttpEntity();
    
    httpEntity.setContent(new ByteArrayInputStream(jsonContent.getBytes()));           
    httppost.setEntity(httpEntity);
    
Alex P
  • 1,721
  • 1
  • 17
  • 18
  • thanks but can you elaborate steps 1 and 2 above of how to convert in to json ? – sjain Jul 31 '13 at 14:20
  • Updated. If you'd like to use `Gson` you will need to download it and put to `assets` folder or add it to Maven's `pom.xml` – Alex P Jul 31 '13 at 14:35
  • putting Gson as a zip or extracted folder ? – sjain Jul 31 '13 at 14:44
  • I downloaded the zip `google-gson-2.2.4-release` and put it in assets folder but its saying `Gson cannot be resolved to a type` when I write code `private static final Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();` – sjain Jul 31 '13 at 14:46
  • Take only the jar out of the zip - `gson-2.2.4.jar`. – Alex P Jul 31 '13 at 14:47
  • `String jsonContent = gson.toJson(inputMap);` Populate the inputMap with all needed parameters as per your example. – Alex P Jul 31 '13 at 14:53
  • Now I am getting `411 Length Required` just like `http://stackoverflow.com/questions/15619562/getting-411-length-required-after-a-put-request-from-http-client` – sjain Jul 31 '13 at 14:58
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/34544/discussion-between-alex-p-and-ved-prakash) – Alex P Jul 31 '13 at 15:03
0

It will work :

    httpPost.addHeader(BasicScheme.authenticate(
            new UsernamePasswordCredentials("email", "password"), "UTF-8", false));