I have upgraded Spring from 3.0.5 to 3.1.1 and stumbled upon a curious issue. Following code worked fine in the previous version:
#RequestMapping("/getPeople")
public Object getPeople()
{
HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity("Hello World", responseHeaders, HttpStatus.OK);
}
But with the latest version I'm getting a 404 error. To resolve this I have to mention the return type as ResponseEntity in the method:
#RequestMapping("/getPeople")
public ResponseEntity getPeople()
{
HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity("Hello World", responseHeaders, HttpStatus.OK);
}
Is this an acceptable workaround or I'm doing something wrong here?
Try the below code. The #ResponseBody annotation is similar to #RequestBody. This annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
#RequestMapping("/getPeople")
#ResponseBody
public Object getPeople()
{
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity("Hello World", responseHeaders, HttpStatus.OK);
}
Related
API response content-type coming as utf-16 but it should be in utf-8 format..am using spring 3.1.0 version. Am passing header and body to resttemplate. Responce comming like ???????????
Help me on this
My Code
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("AuthenticationToken", authenticationToken);
headers.set("ExactSubscriptionId", subscriptionId);``
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity2 = new HttpEntity<String>(lis.toString(),headers2);
ResponseEntity<String> irnResponce2 = restTemplate2.exchange(Url, HttpMethod.POST, entity2,String.class);
i have used resolve this below code
restTemplate2.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
and also tried
headers.add("Accept-Charset", "utf-8");
but in spring 3.1.0 version StringHttpMessageConverter not allowing constructor
I need to resolve in this version only plz anyone help on this
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> c = restTemplate.getMessageConverters();
for(HttpMessageConverter<?> mc :c){
if (mc instanceof StringHttpMessageConverter) {
StringHttpMessageConverter mcc = (StringHttpMessageConverter) mc;
mcc.setWriteAcceptCharset(false);
}
}
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setAcceptCharset(Arrays.asList(Charset.forName("UTF-8")));
HttpEntity<String> entity = new HttpEntity<String>(jsonPayload, headers);
restTemplate.postForEntity(postResourc`enter code here`eUrl, entity, String.class);
I have this :
[HttpDelete]
public HttpResponseMessage DeleteClient(int idCliente)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
how to return a message text next to status?
You could do something like this:
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("The Message")
};
If you want to return JSON (using Newtonsoft.Json library), you could do:
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(
JsonConvert.SerializeObject(new { message = "The Message" }),
Encoding.UTF8, "application/json")
};
Why do you have HttpResponseException in the subject? If you really need to return an error status code with a message while throwing an exception, HttpResponseException has a constructor that takes an HttpResponseMessage instance.
But in .NET Core that exception only in the Microsoft.AspNetCore.Mvc.WebApiCompatShim backwards compatibility package. The recommended way is just to return the HttpResponseMessage with an error status code directly.
I meet a request to upload files with spring resttemplate to upload files
with http header "multipart/form-data", also some other normal parameters need to be posted. how to implements that?
you can use the following code in your application to have both multipartfile and normal request parameters at the same time.
Replace the url with your own.
replace param and value according to your normal parameters.
String url ="http://example.com";
String fileAbsPath ="absolute path of your file";
String fileName = new File(fileAbsPath).getName();
Files.readAllBytes(Paths.get(fileAbsPath));
MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>();
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(Paths.get(fileAbsPath))) {
#Override
public String getFilename() {
return fileName;
}
};
data.add("file", resource);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("file","application/pdf");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("param1", "value1")
.queryParam("param2", "value2")
HttpEntity<> entity =
new HttpEntity<> (data, requestHeaders);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> result =restTemplate.exchange(
builder.toUriString(),
HttpMethod.POST,
entity,
String.class);
System.out.println(result.getBody());
you can use this code.
HttpHeaders headers = getCASHeaders(MediaType.MULTIPART_FORM_DATA);
LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("fileField", new FileSystemResource(""));//get file resource
params.add("stringfield", stringPayload);
HttpEntity requestEntity = new HttpEntity<>(params, headers);
ResponseEntity<CasAssetApiResponse> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
This will send post call with two param, you can add more according to your wish.
Please have a look at this stackoverflow answer as well
I got the error "cannot be cast to java.lang.String" although my code does not have any casting.
I'm trying to POST a XML body to a HTTP endpoint with RESTTemplate, however the following exception is being thrown - "org.springframework.web.client.RestClientException: Cannot extract response: no Content-Type found".
I have checked and the XML file is being posted to the endpoint successfully, however I cannot resolve this exception - clearly I'm doing something wrong. I think I may need to use a HTTP Mapping Converter , but I don't know how to implement this.
def post(String jenkinsURL, String username, String apiCredentials, String jobName) {
RestTemplate rest = new RestTemplate()
String url = "http://$jenkinsURL//createItem?name=$jobName"
def jenkinsConfigPath = "src/main/resources/JenkinsConfig.xml"
def encoding = Base64.getEncoder().encodeToString((username + ":" + apiCredentials).getBytes())
String xmlConfigFile = jenkinsConfigReader.read(jenkinsConfigPath)
HttpHeaders headers = new HttpHeaders()
headers.setContentType(MediaType.APPLICATION_XML)
headers.add("Authorization", "Basic " + encoding)
HttpEntity<String> entity = new HttpEntity<String>(xmlConfigFile, headers)
rest.exchange(url, HttpMethod.POST, entity, String.class)
In Java I wrote a filter like that:
#Provider
public class CorsFilter implements ContainerResponseFilter
{
#Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
throws IOException
{
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
responseContext.getHeaders().add(
"Access-Control-Allow-Headers",
"origin, content-type, accept, authorization, X-Requested-With");
responseContext.getHeaders().add("Access-Control-Allow-Credentials", "false");
responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
if(requestContext.getMethod().equals("OPTIONS"))
{
responseContext.setStatus(200);
}
}
}
Providers are a simply a way of extending and customizing the JAX-RS runtime. Maybe this is a way also for you to solve your problem.
I created the Wep API in ASP.Net core to return the PDF. Here is my code:
public HttpResponseMessage Get(int id)
{
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
var stream = new System.IO.FileStream(#"C:\Users\shoba_eswar\Documents\REquest.pdf", System.IO.FileMode.Open);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "NewTab";
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
return response;
}
But it returns only the JSON response:
{
"version":{
"major":1,
"minor":1,
"build":-1,
"revision":-1,
"majorRevision":-1,
"minorRevision":-1
},
"content":{
"headers":[
{
"key":"Content-Disposition",
"value":[
"attachment; filename=NewTab"
]
},
{
"key":"Content-Type",
"value":[
"application/pdf"
]
}
]
},
"statusCode":200,
"reasonPhrase":"OK",
"headers":[
],
"requestMessage":null,
"isSuccessStatusCode":true
}
Am I doing anything wrong here?
As explained in ASP.NET Core HTTPRequestMessage returns strange JSON message, ASP.NET Core does not support returning an HttpResponseMessage (what package did you install to get access to that type?).
Because of this, the serializer is simply writing all public properties of the HttpResponseMessage to the output, as it would with any other unsupported response type.
To support custom responses, you must return an IActionResult-implementing type. There's plenty of those. In your case, I'd look into the FileStreamResult:
public IActionResult Get(int id)
{
var stream = new FileStream(#"path\to\file", FileMode.Open);
return new FileStreamResult(stream, "application/pdf");
}
Or simply use a PhysicalFileResult, where the stream is handled for you:
public IActionResult Get(int id)
{
return new PhysicalFileResult(#"path\to\file", "application/pdf");
}
Of course all of this can be simplified using helper methods, such as Controller.File():
public IActionResult Get(int id)
{
var stream = new FileStream(#"path\to\file", FileMode.Open);
return File(stream, "application/pdf", "FileDownloadName.ext");
}
This simply abstracts the creation of a FileContentResult or FileStreamResult (for this overload, the latter).
Or if you're converting an older MVC or Web API application and don't want to convert all your code at once, add a reference to WebApiCompatShim (NuGet) and wrap your current code in a ResponseMessageResult:
public IActionResult Get(int id)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = ...
response.Content...
return new ResponseMessageResult(response);
}
If you don't want to use return File(fileName, contentType, fileDownloadName), then the FileStreamResult doesn't support setting the content-disposition header from the constructor or through properties.
In that case you'll have to add that response header to the response yourself before returning the file result:
var contentDisposition = new ContentDispositionHeaderValue("attachment");
contentDisposition.SetHttpFileName("foo.txt");
Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
I couldn't comment the answer by CodeCaster since my reputation isn't high enough.
When trying
public IActionResult Get(int id)
{
using (var stream = new FileStream(#"path\to\file", FileMode.Open))
{
return File(stream, "application/pdf", "FileDownloadName.ext");
}
}
we got a
ObjectDisposedException: Cannot access a disposed object. Object name:
'Cannot access a closed file.'. System.IO.FileStream.BeginRead(byte[]
array, int offset, int numBytes, AsyncCallback callback, object state)
We removed the using
[HttpGet]
[Route("getImageFile")]
public IActionResult GetWorkbook()
{
var stream = new FileStream(#"pathToFile", FileMode.Open);
return File(stream, "image/png", "image.png");
}
And that worked. This is ASP.NET Core 2.1 running in IIS Express.
I don't have enough reputation to post this as a comment, so posting as an answer. The first 3 solutions from #CodeCaster and the solution from #BernhardMaertl are correct.
However, for someone who may not work with files often (like me), please note that if the process running this code (e.g. the API) only has read permissions to the file, you will need to specify that as the third parameter when creating your FileStream, otherwise the default behavior is to open the file for read/write and you will get an exception since you do not have write permissions.
The 3rd solution from #CodeCaster would then look like this:
public IActionResult Get(int id)
{
var stream = new FileStream(#"path\to\file", FileMode.Open, FileAccess.Read);
return File(stream, "application/pdf", "FileDownloadName.ext");
}