使用ApacheHttpClient与数据和标头进行REST调用

时间:2013-10-03 16:33:01

标签: java rest apache-httpclient-4.x rest-client kiicloud

我需要将Kii MbaaS服务集成到我的一个Web应用程序中,而不是移动应用程序。我使用Android SDK并能够连接它。但是对于使用Java解决方案的网站,他们没有任何SDK,并要求我使用REST进行操作。现在我计划使用Servlet中的ApacheHttpClient连接到REST服务。其文档中的REST格式如下所示。在ApacheHttpClient中,我知道我可以将头文件(-H)作为HttpGet.addHeader(“content-type”,“application / json”)传递。但是我不确定如何传递数据(-d)。任何人都可以通过指向任何教程链接或任何有关如何将数据与标题一起传递到REST服务的示例代码来帮助我吗?

REST语法如下 -

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"}'

提前致谢。

-------------------------编辑--------------------- ----------------------------- 这里是我用连接到Apache HttpClient 4.3库编写的示例java代码但是我一直得到错误400 ...有人可以提出建议吗?

错误 -

  

线程“main”中的异常java.lang.RuntimeException:失败:HTTP   错误代码: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();
                }
            }

        }
    }

1 个答案:

答案 0 :(得分:3)

好的,我解决了。我需要以json格式严格地包装数据并发布它,它会起作用。

除了移动应用程序之外,我在其他计划在其网络应用程序中使用Kii MbaaS的人发布了相同内容。

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

    }
}