Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST call using ApacheHttpClient with data and headers

I need to integrate Kii MbaaS services in one of my web application apart from the Mobile apps. I was using the Android SDK and was able to connect it. However for website using Java solution they don't have any SDK and asked me to do th operation using REST. Now I was planning to use ApacheHttpClient from a Servlet to connect to the REST services. The REST format from their docs is given below. In ApacheHttpClient I know I can pass the headers(-H) as HttpGet.addHeader("content-type", "application/json"). However I am not sure how to pass the data (-d). Can anyone help me here by pointing to any tutorial link or any sample code on how to pass data to a REST service along with headers?

The REST syntax is given below-

curl -v -X POST \
  -H "content-type:application/json" \
  -H "x-kii-appid:{APP_ID}" \
  -H "x-kii-appkey:{APP_KEY}" \
  "https://api.kii.com/api/oauth2/token" \
  -d '{"username":"user_123456", "password":"123ABC"}'

Thanks in advance.

------------------------- Edit-------------------------------------------------- here is a sample java code I wrote to connect to using Apache HttpClient 4.3 library however I keep getting error as 400... can anyone pls advice?

error -

Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 400 at com.app.test.RestClientTest.main(RestClientTest.java:49)

package com.app.test;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.MalformedURLException;
    import java.util.ArrayList;
    import java.util.List;

    import org.apache.http.Consts;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;

    public class RestClientTest {

        /**
         * @param args
         */
        public static void main(String[] args) {
            CloseableHttpClient httpClient = null;
            HttpPost httpost = null;
            CloseableHttpResponse response = null;

            try {

                httpClient = HttpClients.createDefault();
                httpost = new HttpPost("https://api.kii.com/api/oauth2/token");
                httpost.addHeader("content-type", "application/json");
                httpost.addHeader("x-kii-appid", "xxxxx");
                httpost.addHeader("x-kii-appkey", "xxxxxxxx");

                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                nvps.add(new BasicNameValuePair("username", "xxxxx"));
                nvps.add(new BasicNameValuePair("password", "xxxxx"));

                // StringEntity input = new
                // StringEntity("{\"qty\":100,\"name\":\"iPad 4\"}");
                // input.setContentType("application/json");
                httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

                response = httpClient.execute(httpost);

                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new RuntimeException("Failed : HTTP error code : "
                            + response.getStatusLine().getStatusCode());
                }

                BufferedReader br = new BufferedReader(new InputStreamReader(
                        (response.getEntity().getContent())));

                String output;
                System.out.println("Output from Server .... \n");
                while ((output = br.readLine()) != null) {
                    System.out.println(output);
                }
            } catch (MalformedURLException e) {

                e.printStackTrace();

            } catch (IOException e) {

                e.printStackTrace();

            } finally {
                try{
                    response.close();
                    httpClient.close();
                }catch(Exception ex) {
                    ex.printStackTrace();
                }
            }

        }
    }
like image 974
Suvoraj Biswas Avatar asked Oct 20 '22 23:10

Suvoraj Biswas


1 Answers

Ok I got it solved. I need to wrap up the data in json format stringentity and post it and it will work.

Here I am posting the same for others who are planning to use the Kii MbaaS in their web apps apart from the Mobile app.

package com.app.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class RestClientTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;

        try {

            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost("https://api.kii.com/api/oauth2/token");

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("content-type", "application/json"));
            nvps.add(new BasicNameValuePair("x-kii-appid", "xxxxx"));
            nvps.add(new BasicNameValuePair("x-kii-appkey", "xxxxxxxxxxxxxx"));

             StringEntity input = new StringEntity("{\"username\": \"dummyuser\",\"password\": \"dummypassword\"}");
             input.setContentType("application/json");
             httpPost.setEntity(input);

            for (NameValuePair h : nvps)
            {
                httpPost.addHeader(h.getName(), h.getValue());
            }

            response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatusLine().getStatusCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (response.getEntity().getContent())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {
            try{
                response.close();
                httpClient.close();
            }catch(Exception ex) {
                ex.printStackTrace();
            }
        }

    }
}
like image 56
Suvoraj Biswas Avatar answered Oct 24 '22 13:10

Suvoraj Biswas