除了移动应用程序之外,我需要将 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();
}
}
}
}