5

除了移动应用程序之外,我需要将 Kii MbaaS 服务集成到我的一个 Web 应用程序中。我正在使用 Android SDK 并且能够连接它。但是对于使用 Java 解决方案的网站,他们没有任何 SDK,并要求我使用 REST 进行操作。现在我打算使用 Servlet 中的 ApacheHttpClient 连接到 REST 服务。下面给出了他们文档中的 REST 格式。在 ApacheHttpClient 中,我知道我可以将 headers(-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。 ..有人可以请教吗?

错误 -

线程“主”java.lang.RuntimeException 中的异常:失败:HTTP 错误代码:com.app.test.RestClientTest.main(RestClientTest.java:49) 处的 400

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

        }
    }
4

1 回答 1

3

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

在这里,我为其他计划在他们的 Web 应用程序中使用 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();
            }
        }

    }
}
于 2013-10-04T20:53:00.563 回答