Java 使用带有数据和标头的 ApacheHttpClient 进行 REST 调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19164494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
REST call using ApacheHttpClient with data and headers
提问by Suvoraj Biswas
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?
除了移动应用程序之外,我需要将 Kii MbaaS 服务集成到我的 Web 应用程序之一中。我正在使用 Android SDK 并且能够连接它。但是,对于使用 Java 解决方案的网站,他们没有任何 SDK,并要求我使用 REST 进行操作。现在我计划使用来自 Servlet 的 ApacheHttpClient 连接到 REST 服务。下面给出了他们文档中的 REST 格式。在 ApacheHttpClient 中,我知道我可以将标头 (-H) 作为 HttpGet.addHeader("content-type", "application/json") 传递。但是我不确定如何传递数据(-d)。任何人都可以通过指向任何教程链接或有关如何将数据与标头一起传递给 REST 服务的任何示例代码来帮助我吗?
The REST syntax is given below-
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"}'
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?
- - - - - - - - - - - - - 编辑 - - - - - - - - - - - - -------------------------- 这是我编写的示例 Java 代码,用于使用 Apache HttpClient 4.3 库进行连接,但是我一直收到 400 错误。 ..有人可以建议吗?
error -
错误 -
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 400 at com.app.test.RestClientTest.main(RestClientTest.java:49)
线程“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();
}
}
}
}
采纳答案by Suvoraj Biswas
Ok I got it solved. I need to wrap up the data in json format stringentity and post it and it will work.
好的,我解决了。我需要以 json 格式严格性包装数据并发布它,它会起作用。
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.
在这里,除了移动应用程序之外,我还为其他计划在其 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();
}
}
}
}