Cleartrip Flight API - "Not authorized to access the service" error - java

I am using Cleartrip Flight API to get flight fare details. When request the URL with API key, i am getting "Not authorized to access the service" error. Here is my Java code using Apache HttpComponents
HttpHost proxy = new HttpHost("My IP", Port No, "http");
String url = "https://api.cleartrip.com/air/1.0/search?from=BOM&to=DEL&depart-date=2013-06-06&return-date=2013-06-06";
//String url = "http://www.google.com/search?q=developer";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("X-CT-API-KEY", "My API Key");
request.addHeader("User-Agent", "Mozilla/5.0");
System.out.println(" header "+request.getHeaders("X-CT-API-KEY")[0]);
HttpResponse response = client.execute(request);
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
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.toString());
}
Can anyone help me !!!

Even i had the same issue. Later i came to know that all the api (which you get during singn up process) are blocked by default. You have to write a mail to api.support#cleartrip.com
They will ask your company details, business model and business case. If they are satisfied with those details then they will unblock your api key.
Since my project is for my final semester they have rejected my api key query.
Here i am sharing my java code. So that it might be useful for some one.
HttpClient client = new DefaultHttpClient();
String getURL =URL;
Log.d("URL",getURL);
HttpGet get = new HttpGet(getURL);
get.setHeader("X-CT-API-KEY", (my api key));
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null)
{
Log.i("GET ", EntityUtils.toString(resEntityGet));
}
Since i was not authorized to use this api i got the following response.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><faults xmlns="http://www.cleartrip.com/apigateway/common"><fault><fault-message>Not authorized to access the service</fault-message></fault></faults>
HTTP URL is as follows
https://api.cleartrip.com/air/1.0/search?from=BOM&to=DEL&depart-date=2013-11-11&return-date=2013-12-12

Related

How to consume Monit Web Service API java

I'm trying to connect with monit web service api (Restful Services), using the following code:
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:2812/z_security_check");
NameValuePair[] credentials = {
new BasicNameValuePair("z_username", "admin"),
new BasicNameValuePair("z_password", "monit"),
new BasicNameValuePair("z_csrf_protection", "off")
};
List<NameValuePair> body = Arrays.asList(credentials);
httpPost.setEntity(new UrlEncodedFormEntity(body));
HttpResponse response = client.execute(httpPost);
System.out.println("Post parameters : " + httpPost.getEntity().getContent());
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
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.toString());
But always I have the same answer:
Post parameters : java.io.ByteArrayInputStream#79d0569b
Response Code : 401
<html><head><title>401 Unauthorized</title></head><body bgcolor=#FFFFFF><h2>Unauthorized</h2>You are not authorized to access monit. Either you supplied the wrong credentials (e.g. bad password), or your browser doesn't understand how to supply the credentials required<hr><a href='http://mmonit.com/monit/'><font size=-1>monit 5.14</font></a></body></html>
Process finished with exit code 0
but when I enter via browser (http: // localhost: 2812 /) asked me the credentials and displays the information correctly
Apparently the web service of monit is available only in the paid version M/Monit, I solve it by making a Web Scraping with jsup of the main page and got the necessary data

Why am I getting HTTP 400 bad request

I am using an HTTP client (code copied from http://www.mkyong.com/java/apache-httpclient-examples/) to send post requests. I have been trying to use it with http://postcodes.io to look up a bulk of postcodes but failed. According to http://postcodes.io I should send a post request to http://api.postcodes.io/postcodes in the following JSON form: {"postcodes" : ["OX49 5NU", "M32 0JG", "NE30 1DP"]} but I am always getting HTTP Response Code 400.
I have included my code below. Please tell me what am I doing wrong?
Thanks
private void sendPost() throws Exception {
String url = "http://api.postcodes.io/postcodes";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("postcodes", "[\"OX49 5NU\", \"M32 0JG\", \"NE30 1DP\"]"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
System.out.println("Reason : "
+ response.getStatusLine().getReasonPhrase());
BufferedReader br = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
result.append(line);
}
br.close();
System.out.println(result.toString());
}
This works, HTTP.UTF_8 is deprecated:
String url = "http://api.postcodes.io/postcodes";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
StringEntity params =new StringEntity("{\"postcodes\" : [\"OX49 5NU\", \"M32 0JG\", \"NE30 1DP\"]}");
post.addHeader("Content-Type", "application/json");
post.setEntity(params);
Jon Skeet is right (as usual, I might add), you are basically sending a form and it defaults to form-url-encoding.
You could try something like this instead:
String jsonString = "{\"postcodes\" : [\"OX49 5NU\", \"M32 0JG\", \"NE30 1DP\"]}";
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
post.setEntity(entity);

HTTP 403 Forbidden coming when using HttpClient authentication mechanism for Sharepoint using NTLM

HTTP/1.1 403 FORBIDDEN
Response content length: 729
Result: soap:ServerException of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.0x8102006d
My concern is how to get authenticated by proxy and also at the same time, to NTLM configured sharepoint in same session? Please help me.
Thanks in advance.
AuthCache authCache = new BasicAuthCache();
HttpHost targetHost = new HttpHost(<sharepointserverhostname>);
NTLMSchemeFactory f = new NTLMSchemeFactory();
HttpContext ctx = new BasicHttpContext();
AuthScheme ns = f.create(ctx);
authCache.put(targetHost, ns);
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(<proxyserverip>, 8080), new UsernamePasswordCredentials ("testdomain\phanigandeed", "Jul#2014"));
credsProvider.setCredentials(
AuthScope.ANY, new NTCredentials("phanigandeed", "Jul#2014", "", "testdomain"));
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
String listName = "PhaniList";
String description = "TestDescription";
String templateID = "101";
// for safety reasons, I had to remove the actual server details.
String endpointURL = <serviceurl>;
String result = "Failed";
String username = "phanigandeed";
String psWord = "Jul#2014";
String domainName = "vsnl";
String XML_DATA = new String("<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><AddList xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\"><listName>"
+ listName
+ "</listName><description>"
+ description
+ "</description><templateID>"
+ templateID
+ "</templateID></AddList></soap:Body></soap:Envelope>");
HttpPost httpPost = new HttpPost(endpointURL);
httpPost.setHeader(new BasicHeader("Content-Type",
"text/xml;charset=UTF-8"));
try {
StringEntity s = new StringEntity(XML_DATA, "UTF-8");
httpPost.setEntity(s);
System.out.println("executing request" + httpPost.getRequestLine());
HttpResponse response = httpclient.execute(httpPost, localContext);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: "
+ entity.getContentLength());
result = EntityUtils.toString(entity);
System.out.println("Result: " + result);
entity.consumeContent();
}
System.out.println("result: " + result);
return;
} catch (Exception e) {
e.printStackTrace();
System.out.println("Sharepoint Create Library failed :"
+ e.getMessage());
return;
}
You need connect to SharePoint and retrieve a digest for authenticating any further requests, that is why it is throwing an exception about your security validation being invalid.
String digest;
try
{
string url = "https://Your.SharePoint.Site";
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
string cmd = "_api/contextinfo";
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json");
client.DefaultRequestHeaders.Add("ContentLength", "0");
StringContent httpContent = new StringContent("");
var response = client.PostAsync(cmd, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
JsonObject val = JsonValue.Parse(content).GetObject();
JsonObject d = val.GetNamedObject("d");
JsonObject wi = d.GetNamedObject("GetContextWebInformation");
digest = wi.GetNamedString("FormDigestValue");
}
}
catch
{
MessageDialog dialog = new MessageDialog("Authentication to server failed. Please try again.");
dialog.ShowAsync();
}
Later you will need to add the digest to the header of your next request to pass along the authentication which would look something like this. This is C# and sorry I don't know the Java specific syntax but you need the Digest to work with Web Services in all platforms:
client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
I have had issues with HTTPClient working with Sharepoint/IIS and NTLM authentication. I was able to get past these issue when I switched to Java HTTPURLConnection. Please see the following posts for reference
HTTP Client and NTLM issue
HTTP Call to Sharepoint fails
Hope this helps you.

Curl to Java Post

How do I do a HTTP GET POST PUT DELETE Request using Java?
I'm using CouchDB and I can post data using cUrl into the database. How do I do the same thing using Java however I cannot find any information on this with good documentation.
curl -X PUT http://anna:secret#127.0.0.1:5984/somedatabase/
Could some please change this cUrl request to Java. Otherwise please recommend me libraries to do so.
Thank You.
You can use HttpClient by Apache.
Here is an example usage of how to call a POST request
String url = "https://your.url.to.post.to/";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("param1", "value1"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
I do recommend that you check this article for more examples.

how to set parameters to server from android application?

I have the following code to connect from my android application to zappos api server and search for some stuff. But It either returns error 404 or We are unable to process the request from the input feilds given.
When I execute the same query it works on the web browser.
The query is:
http://api.zappos.com/Search&term=boots&key=<my_key_inserted_here>
Code:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://api.zappos.com/Search");
NameValuePair keypair = new BasicNameValuePair("key",KEY);
NameValuePair termpair = new BasicNameValuePair("term",data);
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(keypair);
params.add(termpair);
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
String str;
StringBuilder sb = new StringBuilder();
HttpEntity entity =response.getEntity();
if (entity != null) {
DataInputStream in = new DataInputStream(entity.getContent());
while (( str = in.readLine()) != null){
sb.append(str);
}
in.close();
}
Log.i("serverInterface","response from server is :"+sb.toString());
What am I doing wrong?
If I am correct, what you want to do is a GET request with parameters.
Then,the code would looks like something like that:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://api.zappos.com/Search");
HttpParams params = new BasicHttpParams();
params.setParameter("key", "KEY");
params.setParameter("term", "data");
get.setParams(params);
HttpResponse response;
response = client.execute(get);
String str;
StringBuilder sb = new StringBuilder();
HttpEntity entity = response.getEntity();
if (entity != null) {
DataInputStream in;
in = new DataInputStream(entity.getContent());
while ((str = in.readLine()) != null) {
sb.append(str);
}
in.close();
}
Log.i("serverInterface", "response from server is :" + sb.toString());
I found an answer to the question based on ALL of your help. I got the hint that I must search how to connect to REST service and I also used this result. This is the exact result I was looking for. Sadly it resembles too much to what I'm trying to achieve that I think whoever asked it might be applying to the same position :(

Categories