Java – use Apache httpclient to make rest calls with data and headers
In addition to mobile applications, I also need to integrate Kii mbaas services into one of my web applications I use the Android SDK and can connect to it However, for websites using java solutions, they do not have any SDK and require me to use rest for operation Now I plan to use Apache httpclient in servlet to connect to rest service The rest format in the document is as follows In Apache httpclient, I know that I can use the header file (- H) as httpget AddHeader ("content type", "application / JSON") is passed But I'm not sure how to pass the data (- D) Can anyone help me by pointing to any tutorial link or any sample code on how to pass data with a title to a rest service?
The rest syntax is as follows –
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"}'
Thank you in advance
————————-Edit ---- ---- ---- ---- ---- ---- ---- here is the sample java code I wrote by connecting to Apache httpclient 4.3 library, but I have been receiving 400 errors... Can anyone give me some suggestions?
Error –
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();
}
}
}
}
Solution
OK, I'll fix it I need to wrap the data strictly in JSON format and publish it, and it will work
Here, I post the same content as other users who plan to use Kii mbaas in web applications other than mobile applications
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();
}
}
}
}
