Get HTTP code from org.apache.http.HttpResponse - java

I'm using the org.apache.http.HttpResponse class in my Java application, and I need to be able to get the HTTP status code. If I used .toString() on it, I can see the HTTP status code in there. Is there any other function that I can just get the HTTP status code as either an int or String?
Thanks a bunch!

Use HttpResponse.getStatusLine(), which returns a StatusLine object containing the status code, protocol version and "reason".

I have used httpResponse.getStatusLine().getStatusCode() and have found this to reliably return the integer http status code.

httpResponse.getStatusLine().getStatusCode()

A example will be as below,
final String enhancementPayload ="sunil kumar";
HttpPost submitFormReq = new HttpPost("https://bgl-ast/rest/service/form/form-data");
StringEntity enhancementJson = new StringEntity(enhancementPayload);
submitFormReq.setEntity(enhancementJson);
submitFormReq.setHeader("Content-Type", "application/xml");
HttpResponse response = httpClient.execute( submitFormReq );
String result = EntityUtils.toString(response.getEntity());
System.out.println("result "+result);
assertEquals(200, response.getStatusLine().getStatusCode());

Related

How to write / convert CURL for Android java

I am trying to implement the MOT history API https://dvsa.github.io/mot-history-api-documentation/ and they give an example using CURL which works with the supplied api key successfully when using an online CURL tool.
I am trying to implement this in Android and realise I have to use something like HttpPost rather than CURL, this is my code:
//Tried with full URL and by adding the registration as a header.
//HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests?registration=" + reg_selected);
HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json+v6");
httpPost.addHeader("x-api-key", "abcdefgh123456");
httpPost.addHeader("registration", reg_selected);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = response.getEntity().getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = bufferedReader.readLine();
String jsonStr = readLine;
JSONObject myJsonObj = new JSONObject(jsonStr);
}else if (response.getStatusLine().getStatusCode() == 400){
//Bad Request Invalid data in the request. Check your URL and parameters
error_text = "Bad Request";
}else if (response.getStatusLine().getStatusCode() == 403){
//Unauthorised – The x-api-key is missing or invalid in the header
error_text = "Authentication error"; //<<<< FAILS HERE 403
}
response.getStatusLine().getStatusCode() returns • "403 – Unauthorised – The x-api-key is missing or invalid in the header".
However the x-api-key that I use works correctly with the online CURL test so the actual key is correct but how I am adding it to my android code request must be invalid or similar.
Can anyone throw any light as to the correct way to convert the CURL into Android java so that the server does not return 403?
Thanks
It's easy to do with Jsoup:
// CREATE CONNECTION
Connection conn=Jsoup.connect("URL_GOES_HERE");
// ADD POST/FORM DATA
conn.data("KEY", "VALUE");
// ADD HEADERS HERE
conn.header("KEY", "VALUE");
// SET METHOD AS POST
conn.method(Connection.Method.POST);
// ACCEPT RESPONDING CONTENT TYPE
conn.ignoreContentType(true);
try
{
// GET RESPONSE
String response = conn.execute().body();
// USE RESPONSE HERE
// CREATE JSON OBJECT OR ANYTHING...
} catch(HttpStatusException e)
{
int status = e.getStatusCode();
// HANDLE HTTP ERROR HERE
} catch (IOException e)
{
// HANDLE IO ERRORS HERE
}
Ps: I guess you are confused with Header and Post Data. The key etc (Credentials) must be used as Post Data and Content Type etc as Header.

How do we consume rest api with Http basic authentication in spring?

I want to consume rest api from url with http basic authentication that returns a big json & then i want to parse that json without POJO to get some values out of it. How can i achieve that in java spring?
I know this is common question but i could not get proper solution that worked for me.
Please help me someone.
Using the Apache HttpClient, the following Client Code snipped has been copied from the following URL. The comments have been added by myself.
https://www.baeldung.com/httpclient-4-basic-authentication
HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
// Combine the user and password pair into the right format
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
// Encode the user-password pair string in Base64
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.ISO_8859_1));
// Build the header String "Basic [Base64 encoded String]"
String authHeader = "Basic " + new String(encodedAuth);
// Set the created header string as actual header in your request
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));

Getting a 400 after setting json parameters

I am trying to send the following json to a REST server from JAVA
{
"image_url":"image",
"job_fqn":"jobfqn",
"ignore_volumes":true
}
I am setting it as follows in my HttpClient
JSONObject json = new JSONObject();
json.put("image_url","image");
json.put("job_fqn","jobfqn");
json.put("ignore_volumes", "true");
StringEntity params = new StringEntity(json.toString());
post.setEntity(params);
HttpResponse response = client.execute(post);
This gives me a 400, after I remove
json.put("ignore_volumes", "true");
this is a valid input , not sure whats going on. The json from curl works fine, only fails in java
Have you tried json.put("ignore_volumes", true);?
Placing the Boolean true instead of the String true.
Try using true as a boolean and not as a string.
json.put("ignore_volumes", true);

how to insert cypher statement in http post request

I have just started with neo4J and wanted to try the transactional cypher endpoint. I have my neo4J server running on localhost:7474/ and have inserted the movie data.
As stated in the documentation, I have to do a post request and include some parameters. Unfortunately I don't know how I have to include my query in the POST request. As far as I have understood it, I have to pass a JSON String.
private static String sendPost() throws Exception {
String url = "http://localhost:7474/db/data/transaction";
String statement ="[ { \"statement\" : \"MATCH (n:Person) RETURN n.name, n.born\"} ]";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("Accept", "application/json; charset=UTF-8"));
urlParameters.add(new BasicNameValuePair("Content-Type", "application/json"));
urlParameters.add(new BasicNameValuePair("statements", statement));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
StringBuilder builder = new StringBuilder();
builder.append("\nSending 'POST' request to URL : " + url+"<br>");
builder.append("Post parameters : " + post.getEntity()+"<br>");
builder.append("Response Code : " + response.getStatusLine().getStatusCode()+"<br>");
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
result.append("<p>");
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line+"\n");
}
result.append("</p>");
return builder.toString();
}
When I execute the code, I get the following output:
Sending 'POST' request to URL : http://localhost:7474/db/data/transaction
Post parameters : org.apache.http.client.entity.UrlEncodedFormEntity#76adb5f6
Response Code : 415
Can anyone help me on how I have to include my query in the POST request?
http://docs.neo4j.org/chunked/stable/rest-api-transactional.html
Looking at that, you can see the body of your POST request isn't what the server is expecting, i.e. you should be sending an entire JSON document, and not a k/v pair w/ "statements" as a key and your JSON Cypher query as the value. Remember you're sending JSON here, and not a URLEncoded body.
Also, it looks like you're setting the "Accept" and "Content-Type" k/v pairs as part of the POST body when they should, in fact, be part of the headers.
Also also, consider using the Cypher endpoint: http://docs.neo4j.org/chunked/stable/rest-api-cypher.html
HTH

How to pass xml in POST method?

I have to pass xml in a request, but I cannot figure out how can I perform it :/. Can you please help me?
I've already stored and prepared the xml.
The request sample:
POST http://..... HTTP/1.0
Content-type: text/xml
and xml
Thanks in advance
What is the source and destination of your xml?
If your source is say a file, and your destination is say a servlet, you can use curl http://en.wikipedia.org/wiki/CURL to send the xml and a servlet to receive it.
The servlet 3.0 spec has new features for this kind of stuff so that should make it easy.
OR
Are you trying to send a post from your java application?
John : )
Use HttpClient
Following is the code I use to post xml to a server.
String payload = <XML String>
HttpPost post = new HttpPost("http://" + ip + ":" + port);
LOGGER.info("WebService Call for " + ip + ":" + port);
try {
StringEntity entity = new StringEntity(payload);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
HttpEntity resEntity = response.getEntity();
EntityUtils.consume(resEntity);
} finally {
post.releaseConnection();
}

Categories

Resources