I want to consume html response using restTemplate and rerun that response to my html so i can add those content to my html page but getting below error tried so many alternatives but not luck
I want to consume every type of response and return that as it is to my html/jsp via ajax and render that content in a div.
HTML (ajax call) --- Spring MVC (rest call to 3rd party) --- application returns html
Code
#RequestMapping(value = "/xyz-service/**", method = {RequestMethod.GET, RequestMethod.PUT},produces="application/json;charset=UTF-8")
public Object mirrorRest(HttpServletRequest request) {
String url = request.getRequestURI();
return restTemplate.getForObject("http://xyz-service:8080"+url , String.class);
}
I am able to invoke my serive method that retuning html as respose but getting error
"Could not extract response: no suitable HttpMessageConverter found for response type [class java.lang.String] and content type [text/html;charset=UTF-8]"
]
The exception seem to have occurred because your request was missing the header parameters.
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + apikey);
headers.set("Charset", "utf-8");
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Request> entity = new HttpEntity<Request>(
req, headers); //incase if your request have a request body
try {
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); //if no request body you could simply use headers parameter directly
logger.info(response.toString());
return response.getBody().toString();
} catch (HttpStatusCodeException exception) {
logger.info("API failed"+exception);
return null;
}
No you can't. An HTML page is not a json object: REST template is designed to consume RestServices.
You should use a URLConnection from jdk
Related
We have the case where we have two different outcomes on the producer side depending on a request one is for success and on which trows error message.
A simplified sample with two contracts:
1)Contract.make {
request {
method PUT()
urlPath("/sample")
headers {
contentType('application/json')
}
body("{\"acc\": \"1234A\" ,\"case\":\"abc23\",\"re\":2018/12/12}")
}
response {
status BAD_REQUEST()
}
}
2)
Contract.make {
request {
method PUT()
urlPath("/sample")
headers {
contentType('application/json')
}
body("{\"acc\": \"1234\" ,\"case\":\"abc23\",\"re\":2018/12/12}")
}
response {
status 200
}
}
On the consumer side it is able to match both request where as , when i run the invalid request test case it is throwing org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request
But the for both scenarios i can able to see request and coresponding response, i can able to see in the logs
Can any body help me in this?
Thanks
These are my consumer test cases
1) its sucess request scenauro its working fine it is getting 200
enter code here
#Test
public void should_update_case_sucess() throws Exception {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Type", "application/json");
ResponseEntity<String> response = restTemplate.exchange(
"http://localhost:8083//sample",
HttpMethod.PUT,
new HttpEntity<>("{\"acc\":\"1234\",\"case\":\"abc23\",\"re\":\"20181212\"}", httpHeaders), String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200);
}
2)
This is the failure scenario which not getting 400 respose instead it is trowing httpclient error,it is not able to invoke target
enter code here
#Test
public void should_update_case_error() throws Exception {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Type", "application/json");
ResponseEntity<String> response = restTemplate.exchange(
"http://localhost:8083//sample",
HttpMethod.PUT,
new HttpEntity<>("{\"acc\":\"1234A\",\"caseNumber\":\"abc23\",\"representmentStartDate\":\"20181212\"}", httpHeaders), String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(400);
}
Could you help me in this
This will not work cause wiremock has two same requests and two different responses so the first one wins.
What you have to do is to alert the request a little bit to differentiate between the two and that way you'll find the proper response.
In ASP.Net Core 2.0, how can I POST data while redirecting to a third-party URL using Response.Redirect()?
Note: I have to POST this data without using the query-string.
Response.Redirect triggers a GET request which means that the only option is using a query string.
Can you trigger the redirection from the client (if any) in order to make a POST request?
You must use object if you want post data without using query string.
[HttpPost]
public IActionResult Search([FromBody] CustomerSearchRequestApiModel request)
{
if (request == null)
{
return BadRequest();
}
return Ok(request);
}
It is impossible to use Response.Redirect() to send Post request.
For a workaround, you could try HttpClient to send Post request and then return the reponse to the web browser with ContentResult as text/html.
Here is a demo code:
public async Task<ContentResult> HtmlView()
{
using (var formDataContent = new MultipartFormDataContent())
{
HttpClient client = new HttpClient();
Article article = new Article { ArticleName = "AN" };
formDataContent.Add(new StringContent("AN", Encoding.UTF8, "application/json"), "ArticleName");
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage response = await httpClient.PostAsync(#"https://localhost:44393/Articles/Create", formDataContent);
return new ContentResult
{
ContentType = "text/html",
StatusCode = (int)response.StatusCode,
Content = await response.Content.ReadAsStringAsync()
};
}
}
}
Note
Change the HttpClient part to send the right request to your own third party url with validate parameters.
I am making a simple project that uses a Spring RESTApi. I tried to insert data into database using POST request but unfortunately got error there.
I am using Postman for API request.
All other request get, delete and put works fine but post doesn't work.
i have tried inserting data manually without using api but that works fine for me.
The error is;
#RequestMapping(value = "/create", method = RequestMethod.POST)
public ResponseEntity<Void> createUser(#RequestBody User user, UriComponentsBuilder ucBuilder) {
try {
userService.insert(user);
} catch (HibernateException e) {
System.out.println(e);
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getUserId()).toUri());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
POSTMAN
Thanks!!!!!!!!!!!!!!
Cookies added to the HttpServletResponse during an $.ajax POST call do not appear in the response header (there is no set-cookie). The same code does function properly during GET requests.
I have the following code in an interceptor postHandle:
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
.
.
Cookie cookie = new Cookie(User.USER_KEY, userAsJson);
LOGGER.info("Cookie json is: " + userAsJson);
cookie.setPath("/");
response.addCookie(cookie);
LOGGER.info("Header names: " + response.getHeaderNames());
LOGGER.info("Set-cookie header(s): " + response.getHeaders("Set-Cookie"));
}
I'm seeing this issue when returning from a request to this mapping:
#RequestMapping(value = "/api/user/wait", method = RequestMethod.POST)
#ResponseBody
public User waitingApi(HttpSession session) {
Ajax call parameters:
var ajaxMessage = {
url : '/api/user/wait',
type : 'POST',
success : waitCallback,
error : waitErrorCallback
};
On a GET I see the following in my logs:
Cookie json is: { my valid json object }
Header names: [Set-Cookie]
Set-cookie header(s): [user="{ my valid json object }"; Version=1;
Path=/]
On a POST I see the following in my logs:
Cookie json is: { my valid json object }
Header names: [Content-Type, Transfer-Encoding, Date, Server]
Set-cookie header(s): [] <--- this is empty, not redacted
After much time spent with google, I found this post:
http://mjremijan.blogspot.ca/2012/06/spring-not-setting-cookie-on-ajax.html
Is short, the postHandle interceptor doesn't do anything when the request hits an operation which has the annotation #ResponseBody. You can set the cookie inside the operation method by adding the response object to the operation parameters and calling addCookie inside the operation.
In both postHandle and afterCompletion methods it check whether the response is committed or not. Both scenarios are too late to add a cookie.
Set the cookie inside the preHandle and you good to go.
I get this error in my client (an ASP.NET MVC application) from a call to my ASP.NET Web API. I checked and the Web API is returning the data alright.
No MediaTypeFormatter is available to read an object of type
'IEnumerable`1' from content with media type 'text/plain'.
I believe that I can inherit from DataContractSerializer and implement my own serializer which can attach the Content-Type HTTP header as text/xml.
But my question is: is that necessary?
Because if it was, it would mean that the default DataContractSerializer does not set this essential header. I was wondering if Microsoft could leave such an important thing out. Is there another way out?
Here's the relevant client side code:
public ActionResult Index()
{
HttpClient client = new HttpClient();
var response = client.GetAsync("http://localhost:55333/api/bookreview/index").Result;
if (response.IsSuccessStatusCode)
{
IEnumerable<BookReview> reviews = response.Content.ReadAsAsync<IEnumerable<BookReview>>().Result;
return View(reviews);
}
else
{
ModelState.AddModelError("", string.Format("Reason: {0}", response.ReasonPhrase));
return View();
}
}
And here's the server side (Web API) code:
public class BookReviewController : ApiController
{
[HttpGet]
public IEnumerable<BookReview> Index()
{
try
{
using (var context = new BookReviewEntities())
{
context.ContextOptions.ProxyCreationEnabled = false;
return context.BookReviews.Include("Book.Author");
}
}
catch (Exception ex)
{
var responseMessage = new HttpResponseMessage
{
Content = new StringContent("Couldn't retrieve the list of book reviews."),
ReasonPhrase = ex.Message.Replace('\n', ' ')
};
throw new HttpResponseException(responseMessage);
}
}
}
I believe (because I don't have time to test it now) that you need to explicitly set the Status Code on the responseMessage you are passing to HttpResponseException. Normally, HttpResponseException will set the status code for you, but because you are providing a responsemessage explicitly, it will use the status code from that. By default, `HttpResponseMessage has a status code of 200.
So what is happening is you are getting an error on the server, but still returning a 200. Which is why your client is trying to deserialize the text/plain body produced by StringContent, as if it were an IEnumerable.
You need to set
responseMessage.StatusCode = HttpStatusCode.InternalServerError
in your exception handler on the server.
How about just using ReadAsStringAsync if your WebAPI is expecting to return content in plain text?
response.Content.ReadAsStringAsync().Result;