In Java+Spring application I am using, from a third party called over RestTemplate , we get the error response in the JSON with 200 response code.
e.g
{
"errors": [{
"reason": "did not like the request",
"error": "BAD_REQUEST"
}]
}
How can I convert BAD_REQUEST to the 400 integer representations.
Apache HttpStatus inte does not seem to provide any interface to do so.
Maybe you can use org.springframework.http.HttpStatus:
String error = "BAD_REQUEST";
HttpStatus httpStatus = HttpStatus.valueOf(error);
int errorIntCode = httpStatus.value();
or more safe:
String error = "BAD_REQUEST";
HttpStatus httpStatus = Arrays.stream(HttpStatus.values())
.filter(status -> status.name().equals(error))
.findAny()
.orElse(HttpStatus.INTERNAL_SERVER_ERROR);
int errorIntCode = httpStatus.value();
More succinct and short
HttpStatus.OK.value();
Related
So I am trying to create a simple webservice post that consumes json. But I am geting the error RESTEASY002010: Failed to execute: javax.ws.rs.NotSupportedException: RESTEASY003065: Cannot consume content type
My webservice:
#POST
#Produces(MediaType.APPLICATION_XML)
#Path("teste1")
#Consumes(MediaType.APPLICATION_JSON)
public Response teste1(String product) {
String result = "Product created : " + product;
System.out.println("resultado");
System.out.println(result);
return Response.ok() //200
.entity("<erro> none </erro>")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With").build();
}
I also tried to do:
#Consumes("application/json")
But I am getting the same error. I can make it work if I do:
#Consumes("*/*")
But I can't understand why it doesn't work when I say it consumes json. To test the webservice I am using https://apitester.com/. With the folowing Post Data:
{
"key" : "value",
"array" : [
{ "key" : 1 },
{ "key" : 2, "dictionary": {
"a": "Apple",
"b": "Butterfly",
"c": "Cat",
"d": "Dog"
} },
{ "key" : 3 }
]
}
In general the
#Consumes("application/json")
specifies a content media type which webservice can handle.
But also you may need to explicitly specify an appropriate type in the Content-Type header for your request.
I am not familiar with the https://apitester.com but probably it does not send the Content-Type header by default
In such case your server can treat the request body as a plain text, for instance. That request would not be routed to your endpoint, because it is not designed for the plain text.
Setting the #Consumes(*/*) fixes that problem, because the wrong media type matches that pattern as well.
Could you please ensure that you sends the Content-Type: application/json with your POST request?
Studying this SO question ( Authenticated Java Jersey REST call to Bitstamp ), I see that OP had a similar issue. Unfortunately, I can't make the call work in my own implementation: I tried sending key, nonce and signature both via query-parameters as well as json formatted in the request's body. I logged headers and content, so in those two cases, these are the resulting logs:
// send in body
---> POST https://www.bitstamp.net/api/v2/balance/ HTTP/1.1
Accept: application/json;charset=UTF-8
Content-Type: application/json;charset=UTF-8
Content-Length: 140
{"key":"12345678901234567890123456789012","nonce":1234567890,"signature":"1234567890123456789012345678901234567890123456789012345678901234"}
---> END HTTP (140-byte body)
<--- HTTP/1.1 403 Authentication Failed (49ms)
{"status": "error", "reason": "Missing key, signature and nonce parameters.", "code": "API0000"}
<--- END HTTP (96-byte body)
// send as query-parameters
---> POST https://www.bitstamp.net/api/v2/balance/?key=12345678901234567890123456789012&signature=1234567890123456789012345678901234567890123456789012345678901234&nonce=1234567890 HTTP/1.1
Accept: application/json;charset=UTF-8
Content-Type: application/x-www-form-urlencoded
---> END HTTP (0-byte body)
<--- HTTP/1.1 403 Authentication Failed (45ms)
{"status": "error", "reason": "Missing key, signature and nonce parameters.", "code": "API0000"}
<--- END HTTP (96-byte body)
What am I doing wrong? What does bitstamp mean when it states
For a successful authentication you need to provide your API key, a signature and a nonce parameter.
(https://www.bitstamp.net/api/)
I use Feign as REST client. The two methods look like this:
#PostMapping(value = "api/v2/balance/", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
ResponseEntity<Map<String, Object>> getAccountBalanceQuery(#RequestParam("key") String key,
#RequestParam("signature") String signature,
#RequestParam("nonce") Integer nonce);
#PostMapping(value = "api/v2/balance/", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
ResponseEntity<Map<String, Object>> getAccountBalanceBody(#RequestBody BitstampAuth body);
Thanks!
I need to receive JSON data from this Api http://countryapi.gear.host/v1/Country/getCountries using REST API. I need to receive NativeName and Region for the specific country.
My main problem is how to send request for the specific country (for example I print Name Australia) and get the response for NativeName and Region - Australia, Oceania (it should be String).
I have such classes:
public class Client {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient clientGetEntity = new DefaultHttpClient();
HttpGet request = new HttpGet("http://countryapi.gear.host/v1/Country/getCountries?pName=Australia");
request.addHeader("accept", "application/json");
HttpResponse responseGetEntity = clientGetEntity.execute(request);
//String json =EntityUtils.toString((HttpEntity) responseGetEntity);
System.out.println("Request : " + request.toString());
System.out.println("Response : " + responseGetEntity.toString());
}
}
EDITS
As regards getting the specific country's name, you need to make a get request with the country name such as:
http://countryapi.gear.host/v1/Country/getCountries?pName=Australia
The response from this request:
{
"IsSuccess": true,
"UserMessage": null,
"TechnicalMessage": null,
"TotalCount": 1,
"Response": [
{
"Name": "Australia",
"Alpha2Code": "AU",
"Alpha3Code": "AUS",
"NativeName": "Australia",
"Region": "Oceania",
"SubRegion": "Australia and New Zealand",
"Latitude": "-27",
"Longitude": "133",
"Area": 7692024,
"NumericCode": 36,
"NativeLanguage": "eng",
"CurrencyCode": "AUD",
"CurrencyName": "Australian dollar",
"CurrencySymbol": "$",
"Flag": "https://api.backendless.com/2F26DFBF-433C-51CC-FF56-830CEA93BF00/473FB5A9-D20E-8D3E-FF01-E93D9D780A00/files/CountryFlags/aus.svg",
"FlagPng": "https://api.backendless.com/2F26DFBF-433C-51CC-FF56-830CEA93BF00/473FB5A9-D20E-8D3E-FF01-E93D9D780A00/files/CountryFlagsPng/aus.png"
}
]
}
You can access NativeName and region by:
data.Response[0].NativeName and data.Response[0].Region respectively.
Since the data returned from the API is always a JSON string, dont forget to parse the string before use.
----------------------------------------
I am not a java developer but I have dealt with a lot of JSON data, Also C# and TypeScript projects.
First, you should take a look at this line:
request.addHeader("accept", "application/fson");
Am afraid this is not a valid JSON request header and if we where to start debugging your code, it would be difficult to pinpoint where the problem lies if the basis of the whole request is faulty. Please correct to:
request.addHeader("accept", "application/json"); and try again, if you have the same result, we can continue debugging from there.
JSON file
[ { customerId:1}, { customerId:2 }, { customerId:3>} ]
in JAVA with
Response resp = when().get("link");
i received the json to resp file.
Now from the resp file - i'm tring to create a arrray - soo that all the values of the customerId is saved in that array using the below code
ArrayList list = resp
.then()
.contentType(ContentType.JSON)
.extract()
.path(".customerId");
but its not working.
can someone help me out.?
Is possible to filter the response by date?
For example, my report query pulls data for 7daysago. But I want to filter this data for each day. This way I don't have to run GoogleAnalytics query every day. Tried using the ga:date dimension as filter but it did not work.
DimensionFilter filter = new DimensionFilter()
.setDimensionName("ga:date").setOperator("LESS_THAN")
.setExpressions(Arrays.asList("today"));
Stacktrace:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code": 400,
"errors": [
{
"domain": "global",
"message": "Invalid value at 'report_requests[0].dimension_filter_clauses[0].filters[0].operator' (TYPE_ENUM), \"LESS_THAN\"",
"reason": "badRequest"
}
],
You can try the core reporting api v4. It offers the dateRange parameter. Let me know if you need some code. For example:
ReportRequest request = new ReportRequest()
.setViewId(VIEW_ID)
.setDateRanges(Arrays.asList(dateRangessArray))
.setDimensions(Arrays.asList(dimensionsArray))
.setMetrics(Arrays.asList(metricsArray))
.setOrderBys(Arrays.asList(orderBy))
.setPageToken(pageToken)
.setPageSize(10000);
where the dateRangesArray could be:
DateRange dateRange = new DateRange();
dateRange.setStartDate(startDate);
dateRange.setEndDate(endDate);
dateRangessArray[0]=dateRange;
The startDate and endDate are strings in the date format: yyyy-mm-dd