Here is my code :
#RequestMapping(value = "/report/download", method = RequestMethod.GET,produces="application/vnd.ms-excel")
public Response getReportFile(#QueryParam("reportid") Long reportId)
{
System.out.println("Param"+reportId);
Long n=(long) 10;
String json=reportService.getReportFile(n);
File file = new File("D:\\Agent Information.xls");
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition","attachment; filename=Sample.xls");
return response.build();
}
i am getting the below Error in java console: Handler execution resulted in exception: Could not find acceptable representation
Your webservice is saying that the response type it is returning is not provided in the Accept HTTP header in your Client request.
So while making HTTP Request you have to add 'Accept Headers' . If it's JSON request then you will add 'Accept : application/json'. Similarly for your current example it will be
'Accept: text/plain'
'Accept-Charset: utf-8'
Find all accept headers here. And follow this steps to resolve
1) Find out the response (content type) returned by web service.
2) Provide this (content type) in your request Accept header.
Related
Im having problems on posting a multipart/formdata request to a REST api. The request returns an 400 Bad Request response.
This is how the request should look like. The link shows you a screenshot captured on a successful request by the web interface.
Successful request
This is the Java code I created.
public void importModel(String projectId, String modelId, MultipartFile file, String fileName) throws IOException {
MultipartBodyBuilder builder = new MultipartBodyBuilder();
builder.part("data", file.getBytes(), MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", "form-data; name=data; filename=" + fileName);
MultiValueMap<String, HttpEntity<?>> parts = builder.build();
WebClient webClient = WebClient.builder()
.filters(exchangeFilterFunctions -> {
exchangeFilterFunctions.add(logRequest());
exchangeFilterFunctions.add(logResponse());
})
.build();
String request = webClient.post()
.uri(getBaseUriBuilder()
.pathSegment(getTeamSlug())
.path(API_PATH_PROJECTS)
.pathSegment(projectId)
.path(API_PATH_MODEL)
.pathSegment(modelId)
.path("/importasync")
.build())
.contentType(MediaType.MULTIPART_FORM_DATA)
.contentLength(file.getSize())
.header(HttpHeaders.AUTHORIZATION, getPrefixedAuthToken())
.body(BodyInserters.fromMultipartData(parts))
.exchange()
.flatMap(FlatService::apply)
.block();
return;
}
Any help is much appreciated. Thank in advance!
Have you tried to send the request with alternative Software like POSTMAN.
There you can check for the request properties that are being sent with the request
a 400 error can occur due to the following issues with your request
Wrong URL: Same as 404-Error a Bad Request is generated, when the user types in a wrong internet address or he adds special chars to the address.
Error full Cookies: If the Cookie inside your browser is to old or broken it can also be a 400.
Old outdated DNS-Entries: In your DNS-Cache could lie files that point to wrong or outdated IP- addresses
Too big files: when you try to upload very large files, the server can deny the request.
Too long header lines: the communication between the client and server is done with header information about the request. some servers set a limit to the header length.
Also if you can find out the more specific 400 error like this:
400.1: Invalid Destination Header
400.2: Invalid Depth Header
400.3: Invalid If Header
400.4: Invalid Overwrite Header
400.5: Invalid Translate Header
400.6: Invalid Request Body
400.7: Invalid Content
400.8: Invalid Timeout
400.9: Invalid Lock Token
If you are not the server admin you could ask him about specifications of the server. or use tools like postman where you can try to send requests to the server and find out more specific error codes.
I'm able to test my REST API through postman client and its giving me the expected response. But, when I try to test through junit, its giving 400 status code
Content type is application/json as per the payload
final static String ROOT_URI = "http://localhost:7000/employees";
#Test
public void simple_get_test() {
Response response = get(ROOT_URI + "/list?emp=100");
}
Am I missing anything
Try setting the port using RestAssured.port = 7000 and remove it from the URI. It would be usefull if you post the response message aside from the code.
I have Java spring server that requires the Content-Type of the requests being sent to the server to be multipart/form-data.
I can correctly send requests to the server with postman:
However, I got The current request is not a multipart request error when trying to send the request with requests module in python3.
My python code is:
import requests
headers = {
'Authorization': 'Bearer auth_token'
}
data = {
'myKey': 'myValue'
}
response = requests.post('http://127.0.0.1:8080/apiUrl', data=data, headers=headers)
print(response.text)
If I add 'Content-Type': 'multipart/form-data' to the header of the request, the error message then becomes Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found.
How can I make the same request as postman sends with python?
requests's author thinks this situation is not pythonic, so requests doesn't support this usage natively.
You need to use requests_toolbelt which is an extension maintained by members of the requests core development team, doc, example:
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
m = MultipartEncoder(
fields={'field0': 'value', 'field1': 'value',
'field2': ('filename', open('file.py', 'rb'), 'text/plain')}
)
r = requests.post('http://httpbin.org/post', data=m,
headers={'Content-Type': m.content_type})
I'm building a Jersey 2 client, which calls a service to get a file from the server.
The service returns binary file content as application/octet-stream
NOw, this is my code where I call the webservice
Response response = target.request().header(HttpHeaders.COOKIE, this.cookie)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM)
.accept(MediaType.APPLICATION_OCTET_STREAM).get();
I get a HTTP 200 Response. But i don't understand how I can get the file content from the response.
EDIT
The service documentation says "To GET the binary file content and the metadata, use header Accept: multipiart/mixed"
So, I tried the below
Response response = target.request()
.header(HttpHeaders.COOKIE, this.cookie)
.header(HttpHeaders.CONTENT_TYPE, "multipart/mixed")
.accept("multipart/mixed").get();
Even here, I get a HTTP status 200 response. But How do I read the file content??
Please help!!
Take a look at the documentation you will see that response has a readEntity method that you can use to read the inputstream:
InputStream in = response.readEntity(InputStream.class);
... // Read from the stream
in.close();
I am running a rest POST request and I am getting this error when I compile:
Caught: java.lang.IllegalArgumentException: No encoder found for request content type */*
Here is my code:
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )
import groovyx.net.http.RESTClient
def client = new RESTClient( 'http://localhost' )
def resp = client.post( path : '/services/adi/validateadimeta/fromfile',body : [ file:'foo' ] )
I am not sure if its responding or not maybe its a rencoding problem with the response? The */* has me concerned that its not even making a connection. When I run this as a CURL command on the commandline it works fine.
file is the only parameter needed for this post call.
Thanks
Refer docs on http-builder. Specifically,
Since we never set a default content-type on the RESTClient instance
or pass a contentType argument in this request, RESTClient will put
Accept: / in the request header, and parse the response based on
whatever is given in the response content-type header.
Modify, post() call as below:
#Grab('org.codehaus.groovy.modules.http-builder:'http-builder:0.7' )
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.*
def client = new RESTClient( 'http://localhost' )
def resp = client.post(
path: '/services/adi/validateadimeta/fromfile',
body : [ file : 'foo' ],
requestContentType : JSON
)
When i add "requestContentType : JSON", it returned "Bad request"
It's changed to "requestContentType: URLENC", it works for me.
Read documentation of RESTClient it explained for me
Note that the above example is posting the request data as
application/x-www-form-urlencoded. (The twitter API doesn't support
XML or JSON POST requests.) For this reason, a requestContentType
parameter must be specified in order to identify how the request body
should be serialized.
Since we never set a default content-type on the RESTClient instance
or pass a contentType argument in this request, RESTClient will put
Accept: / in the request header, and parse the response based on
whatever is given in the response content-type header. So because
Twitter correctly identifies its response as application/json, it will
automatically be parsed by the default JSON parser.