REST call using ApacheHttpClient with data and headers - java

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?
The REST syntax is given below-
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?
error -
Exception in thread "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();
}
}
}
}

Ok I got it solved. I need to wrap up the data in json format stringentity and post it and it will work.
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.
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();
}
}
}
}

Related

How can I upload pdf files in Egnyte using Rest API and Java

Having the PDF files in local drive(D:). Need to upload those PDF files in Egnyte with the help of Rest API and Java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
#SuppressWarnings("deprecation")
public class Postrequest {
public static void postRequest(String attachmentValue) throws Exception {
String attachment = "C:\\Users\\eclipse-workspace\\renamedfile\\"+attachmentValue;
String url = "https://domain.egnyte.com/pubapi/v1/fs-content/Shared/a/Sa/Upload/"+attachmentValue;
File inFile = new File(attachment);
FileInputStream fis = null;
FileBody data = new FileBody(inFile);
try {
fis = new FileInputStream(inFile);
HttpClient httpclient = HttpClientBuilder.create().build();
// server back-end URL
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Authorization", "Bearer " + "*****");
httppost.addHeader("Content-Disposition", "form-data; name=\"file\"");
//httppost.addHeader("Content-type", "****");
httppost.addHeader("Content-type", "text/plain");
httppost.addHeader("Host", "domain.egnyte.com");
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("document", data);
HttpEntity httpEntity = entity.build();
httppost.setEntity(httpEntity);
// execute the request
HttpResponse response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
Assert.assertEquals(statusCode, 200,"The Status code is not matched");
HttpEntity responseEntity = response.getEntity();
String responseString = EntityUtils.toString(responseEntity, "UTF-8");
System.out.println("[" + statusCode + "] " + responseString);
} catch (ClientProtocolException e) {
System.err.println("Unable to make connection");
} catch (IOException e) {
System.err.println("Unable to read file");
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
}
}
};

How to send https post request to with parameter to an api

I'm trying to send https post request to my api that send json response, this is a search function so it will require 1 parameter, but i cannot get the expected result from my api, here are my code
Handler.java
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class Handler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public Handler(){
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method, List<NameValuePair> params){
try {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
HttpParams params2 = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(params2, schemeRegistry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params2);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
if(method == POST){
HttpPost httpPost = new HttpPost(url);
if(params != null){
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e){
Log.e("Buffer Error", "Error : " + e.toString());
}
return response;
}
makeServiceCall is used to make the request to url, but it only works with GET request and couldnt work with POST request, how do i fix this?

Java client with Apache HttpClient to connect to Druid

I am working on ingesting and query data on Druid Server. But, when I query I just using the command line as below:
curl -X 'POST' -H 'Content-Type:application/json' -d #quickstart/ingest_statistic_hourly_generate.json localhost:8090/druid/indexer/v1/task
Can anyone tell me the way of utilizing Java client with Apache HttpClient to send that query to Druid server so as to get response. Thanks so much.
I have not tested this , but this should give you a fair idea of doing this
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
public class HTTPTestClient {
public static void main(String[] args) throws Exception {
String url = "http://localhost:8090/druid/indexer/v1/task";
String content = new String(Files.readAllBytes(Paths.get("quickstart/ingest_statistic_hourly_generate.json")));
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");
post.addHeader("charset", "UTF-8");
post.addHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(content));
HttpResponse response = client.execute(post);
System.out.println(response.getStatusLine());
System.out.println("Response Code : " + response);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result);
}
}

Understanding REST create request url

What will be the url for creating an entity say myEntity through a rest url? myEntity has two parameter name and description. Here is how rest controller looks like:
#POST
#Path("/create")
#Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createJobType(MyEntity myEntity) {}
If it looks ok then how would myEntity parameters will passed through request url?
It's test class:
#Test
public void testShouldCreateMyEntity() {
MyEntity entity = new MyEntity();
entity.setName("Sample Name");
entity.setDescription("Sample Description);
String url = buildRequestURL("/create/"+entity).toUrl(); // Confused :(
}
Not sure if I should pass entity with URL. If not then how the entity would be passed?
There are many ways of testing your endpoint, and these tests might vary according to your needs.
For example, if authentication is required, or if HTTPS is required.
But supposing you don't need authentication and HTTPS is not used, you can test your endpoint with this code:
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;
import com.google.gson.Gson;
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("http://localaddressportetc.../create"); // <-- I suggest you change this to "entity" since this is what is being created by the POST
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("content-type", "application/json"));
MyEntity entity = new MyEntity();
entity.setName("Sample Name");
entity.setDescription("Sample Description");
Gson gson = new Gson();
String entityJSON = gson.toJson(entity);
StringEntity input = new StringEntity(entityJSON);
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();
}
}
}
}

HTTPclient POST with problematic web site

I'm trying to retrive some data from a web site.
I wrote a java class which seems to work pretty fine with many sites but it doesn't work with this particular site, which use extensive javascript in the input fomr.
As you can see from the code I specified the input fields taking the name from the HTML source, but maybe this website doesn't accept POST request of this kind?
How can I simulate an user-interaction to retrieve the generated HTML?
package com.transport.urlRetriver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class UrlRetriver {
String stationPoller (String url, ArrayList<NameValuePair> params) {
HttpPost postRequest;
HttpResponse response;
HttpEntity entity;
String result = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
postRequest = new HttpPost(url);
postRequest.setEntity((HttpEntity) new UrlEncodedFormEntity(params));
response = httpClient.execute(postRequest);
entity = response.getEntity();
if(entity != null){
InputStream inputStream = entity.getContent();
result = convertStreamToString(inputStream);
}
} catch (Exception e) {
result = "We had a problem";
} finally {
httpClient.getConnectionManager().shutdown();
}
return result;
}
void ATMtravelPoller () {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(2);
String url = "http://www.atm-mi.it/it/Pagine/default.aspx";
params.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_afa5adbb_5b60_4e50_8da2_212a1d36e49c$txt_address_s", "Viale romagna 1"));
params.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_afa5adbb_5b60_4e50_8da2_212a1d36e49c$txt_address_e", "Viale Toscana 20"));
params.add(new BasicNameValuePair("sf_method", "POST"));
String result = stationPoller(url, params);
saveToFile(result, "/home/rachele/Documents/atm/out4.html");
}
static void saveToFile(String toFile, String pos){
try{
// Create file
FileWriter fstream = new FileWriter(pos);
BufferedWriter out = new BufferedWriter(fstream);
out.write(toFile);
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
}
At my point of view, there could be javascript generated field with dynamic value for preventing automated code to crawl the site. Send concrete site you want to download.

Categories

Resources