Error 404 with Java HttpClient - java

I am using Java HttpClient package to make http requests. But I am getting 404. When I try the same request with curl, it works fine. Here's the curl request -
curl -i -X POST http://api/endpoint -H "Content-Type: application/json" -d 'content'
Here's the java code that I am using to implement the above curl request -
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("http://api/endpoint");
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(content));
HttpResponse response = client.execute(post);
logger.info("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);
}
logger.info("Response details "+result);
I see error 404 NOT FOUND when I run this java code. What could the problem be?

Remove post.setHeader("Accept", "application/json");

Related

curl and Java program are treated differently by CouchDB

This question might be a little bit naive...
I have written a small Java program that should query a CouchDB instance. However, CouchDB constantly returns that my user is not authorized. Using the same URL with curl works.
The Java Code:
HttpGet request = new HttpGet("http://admin:PASSWORD#localhost:5984/ecm_ng_nonpart/_security");
request.addHeader("accept", "application/xml");
try {
System.out.println("Executing request " + request.getMethod() + " " + request.getUri());
ClassicHttpResponse resp = httpClient.execute(request);
BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
The response:
{"error":"unauthorized","reason":"You are not authorized to access this db."}
The curl output:
C:\Users\joche>curl -X GET http://admin:PASSWORD#localhost:5984/ecm_ng_nonpart/_security
{"members":{"roles":["_admin"],"names":["ecmnp","admin"]},"admins":{"roles":["_admin"],"names":["admin"]}}
Any idea what I am doing wrong?
Using the same URL with curl works.
Your posted information does not support this claim. Your URLs are different in the two cases.
Java: _sessions
HttpGet request = new HttpGet("http://admin:PASSWORD#localhost:5984/ecm_ng_nonpart/_sessions");
Curl: _security.
curl -X GET http://admin:PASSWORD#localhost:5984/ecm_ng_nonpart/_security

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);

What is the Java equivalent for the following in curl?

curl https://view-api.box.com/1/documents \
-H "Authorization: Token YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://cloud.box.com/shared/static/4qhegqxubg8ox0uj5ys8.pdf"}' \
-X POST
How do you accomodate the url?
This is what I tried so far.
final String url = "https://view-api.box.com/1/documents";
#SuppressWarnings("resource")
final HttpClient client = HttpClientBuilder.create().build();
final HttpPost post = new HttpPost(url);
post.setHeader("Authorization", "Token: TOKEN_ID");
post.setHeader("Content-Type", "application/json");
final List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("url", "https://cloud.box.com/shared/static/4qhegqxubg8ox0uj5ys8.pdf"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
final HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
final BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
final StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
}
You have everything ok except the entity, what you're sending in curl is not the content of an html form but a json object.
First take off this part (don't send your data as if it were application/x-www-form-urlencoded):
// comment out / delete this from your code:
final List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("url", "https://cloud.box.com/shared/static/4qhegqxubg8ox0uj5ys8.pdf"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
And then add the body in this way:
BasicHttpEntity entity = new BasicHttpEntity();
InputStream body = new ByteArrayInputStream(
"{\"url\": \"https://cloud.box.com/shared/static/4qhegqxubg8ox0uj5ys8.pdf\"}".getBytes());
entity.setContent(body);
post.setEntity(entity);
I'm assuming that your JSON string only have chars between 0x20 and 0x7F, but if you use other characters (like Ñ) then you need to transform your data to a bytearray using the encoding UTF-8 (the standard encoding used in JSON data) in this way:
BasicHttpEntity entity = new BasicHttpEntity();
String myData = "{\"url\": \"https://cloud.box.com/shared/static/4qhegqxubg8ox0uj5ys8.pdf\"}";
ByteArrayOutputStream rawBytes = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(rawBytes,
Charset.forName("UTF-8"));
writer.append(myData);
InputStream body = new ByteArrayInputStream(rawBytes.toByteArray());
entity.setContent(body);
post.setEntity(entity);
I would suggest the following - although I can't remember if the StringEntity is available under HTTPClient
final String url = "https://view-api.box.com/1/documents";
#SuppressWarnings("resource")
final HttpClient client = HttpClientBuilder.create().build();
final HttpPost post = new HttpPost(url);
post.setHeader("Authorization", "Token: TOKEN_ID");
post.setHeader("Content-Type", "application/json");
post.setEntity(new StringEntity("{\"url\": \"https://cloud.box.com/shared/static/4qhegqxubg8ox0uj5ys8.pdf\"}"));
final HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
final BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
final StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
}

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.

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

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

Categories