Calling a different host from Spring Controller - spring

My localhost is : http://localhost:8585/api/getproducts where i use #Requestmapping(/api/getproducts) in my ProductController to get to my product page.
On click of a button, i need to call an api on a different host :
http://10.120.130.22:9292/ and i tried to use the below code in a new Controller to call the host:
#RequestMapping("Trainer/reStaff/")
#RequestMapping(method = RequestMethod.POST)
public #ResponseBody response(#RequestParam("trainingId") final int trainingId, HttpServletRequest request)
throws ClientProtocolException, IOException {
String hostname="http://10.120.130.22:9292/";
CloseableHttpClient httpclient = HttpClients.custom().build();
CloseableHttpResponse response=null;
try{
String uri=hostname+"Trainer/reStaff/?trainingId="+trainingId;
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
response = httpclient.execute(httpPost);
String responseData = EntityUtils.toString(response.getEntity());
if(response.getStatusLine().getStatusCode()==200)
System.out.println(responseData+"\n");
else
System.out.println("Error :" + responseData+"\n");
}finally {
httpclient.close();
response.close();
}
But i get the error : HTTP Status 404 - type Status reportmessage description The requested resource is not available.
How do i call the new host from my controller?

I understood how this works. We need to pass the url through httpPost in the service layer :
HttpPost httpPost = new HttpPost(hostUri);
JsonObject jsonResponse = null;
try {
String httpRequestBody = jsonRequestBuilder.build().toString();
logger.info("Request Body: " + httpRequestBody);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(httpRequestBody));
HttpResponse httpResponse = httpClient.execute(httpPost);
logger.debug("Response Status: " + httpResponse.getStatusLine().getStatusCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line;
StringBuffer httpResponseBody = new StringBuffer();
while ((line = reader.readLine()) != null) {
httpResponseBody.append(line);
}
logger.info("Response Body: " + httpResponseBody.toString());
JsonReader jsonReader = Json.createReader(new StringReader(httpResponseBody.toString()));
jsonResponse = jsonReader.readObject();
jsonReader.close();
} catch (Exception ex) {
logger.error("Error occurred while invoking POST on ep: " + hostUrl, ex);
} finally {
httpPost.releaseConnection();
}
logger.debug("Exiting");
return jsonResponse;

Related

How to Redirect request as post using ResponseEntity

I trying to include response from other url from ResponseEntity for oauth authorization but it is failing as I am unable to specify request method.
Below is the code
#RequestMapping(value = "/login/otp", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
#ResponseBody
public ResponseEntity<?> getOTP(#Valid #RequestBody String loginDtls,UriComponentsBuilder ucBuilder) {
LoginDAO login = null;
ResponseEntity<?> resp = null;
try {
ObjectMapper mapper = new ObjectMapper();
String userId = "";
try {
JsonNode root = mapper.readTree(loginDtls);
userId = root.get("userId").textValue();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("UserController : getting otp for contact "+ userId);
login = loginService.findByUserId(userId);
if (login==null) {
System.out.println("A UserDAO with name " + userId + " does not exist");
resp = new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
String otp = GenUtil.generateOTP();
LoginDAO loginUpd = new LoginDAO(login);
loginUpd.setOtp(otp);
loginUpd.setOtpTimestamp(new Timestamp(System.currentTimeMillis()));
loginService.updateLogin(loginUpd);
System.out.println(loginUpd);
resp = getAuthenticated(ucBuilder);
System.out.println(resp.getStatusCodeValue());
System.out.println(resp.getBody());
}catch(Exception e) {
e.printStackTrace();
}
resp = new ResponseEntity<String>(login.toString(), HttpStatus.OK);
return resp;
}
private ResponseEntity<?> getAuthenticated(UriComponentsBuilder ucBuilder){
HttpHeaders headers = new HttpHeaders();
URI uri= ucBuilder.path("/oauth/token"+PASSWORD_GRANT).build().toUri();
List<MediaType> accept = new ArrayList<MediaType>();
accept.add(MediaType.APPLICATION_JSON_UTF8);
headers.setAccept(accept);
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.setBasicAuth("my-trusted-client", "secret");
System.out.println(headers);
ResponseEntity<?> resp = ResponseEntity.created(uri).headers(headers).build();
return resp;
}

Spring Restful Mutipart

I would like to ask information regarding Multipart/Form-data, if these are compatible with RequestMethod.GET?
In my case I have to return a file + JSON in one response. (Note: File should not be inside the JSON). Sample response:
FILE
{
"id":"1234",
"name":"question Man"
}
I think this might be helpful, please modify it as of your needs.
#RequestMapping(value = URIConstansts.GET_FILE, produces = { "application/json" }, method = RequestMethod.GET)
public #ResponseBody ResponseEntity getFile(#RequestParam(value="fileName", required=false) String fileName,HttpServletRequest request) throws IOException{
ResponseEntity respEntity = null;
byte[] reportBytes = null;
File result=new File("/filepath/"+fileName);
if(result.exists()){
InputStream inputStream = new FileInputStream("/filepath/"+fileName);
String type=result.toURL().openConnection().guessContentTypeFromName(fileName);
byte[]out=org.apache.commons.io.IOUtils.toByteArray(inputStream);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("content-disposition", "attachment; filename=" + fileName);
responseHeaders.add("Content-Type",type);
respEntity = new ResponseEntity(out, responseHeaders,HttpStatus.OK);
}else{
respEntity = new ResponseEntity ("File Not Found", HttpStatus.OK);
}
return respEntity;
}

Issue in downloading zip file in Spring REST Service

My API is as follows:
#ApiOperation(value = "Zip of all the documents the customer attached to their application (id and loan)", notes = "", response = Void.class, tags = {
"Manage Customers/Applications",
})
#ApiResponses(value = {
#ApiResponse(code = 200, message = "OK", response = Void.class)
})
#RequestMapping(value = idPath + "/files/customer-documents/zip",
method = RequestMethod.GET)
#ResponseBody
void downloadCustomerDocumentsAsZip(HttpServletResponse response,
#ApiParam(value = "Application ID", required = true) #PathVariable(value = "applicationId")
Long applicationId);
The Rest Controller:
#Override
public void downloadCustomerDocumentsAsZip(HttpServletResponse response,
#ApiParam(value = "Application ID", required = true) #PathVariable(value = "applicationId")
Long applicationId) {
InputStream inputStream = new ByteArrayInputStream(manageApplicationsService.findCustomerDocumentsAsZip(applicationId));
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Disposition", "attachment; filename=zipFile.zip");
try {
FileCopyUtils.copy(inputStream, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
The Response:
PK{i�Jtemp0+I�(Q(A%
Issue:
I want to download the zip file as an attachment, but the response is as above.
Note:
I tried all the download methods which are explained on Rest Download Endpoints but none of them were successful. I also add
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
to the API definition but again no success.
So, I would be so grateful if anyone could help me with their genuine solution.
I had the same issue. Changing Content-Type to MediaType.APPLICATION_PDF_VALUE triggered download action for me. But then "Save As" dialog display filename extension as .pdf by default.
With HttpServletResponse
response.setContentType(MediaType.APPLICATION_PDF_VALUE);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
response.setContentLength((int)contents.length);
try {
response.getOutputStream().write(contents);
response.getOutputStream().flush();
} catch (IOException e) {
throw new BadRequestException("Could not generate file");
}
Of if you use ResponseEntity
byte[] contents = fileContent.getBytes();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
responseHeaders.add(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_PDF_VALUE);
return new ResponseEntity<byte[]>(contents, responseHeaders,HttpStatus.OK);
You can just return a ResponseEntity<byte[]> in your controller. Add Content-Type and Content-Disposition headers to your response so that it opens properly.
public ResponseEntity<byte[]> downloadCustomerDocumentsAsZip(
#ApiParam(value = "Application ID", required = true)
#PathVariable(value = "applicationId") Long applicationId) {
byte[] bytes = manageApplicationsService.findCustomerDocumentsAsZip(applicationId);
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Content-Type", "application/octet-stream");
headers.add("Content-Disposition", "attachment; filename=\"zipFile.zip\"");
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}
According to HttpServletResponse doc: calling flush() commits the response. I think you need to call response.getOutputStream().flush(); if you want to use HttpServletResponse. Otherwise, Tim's answer provides an easier way to do it.
You can set the media type as: application/json;charset=UTF-8 by using:
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON_UTF8);

restTemplate.postForObject org.springframework.web.client.HttpClientErrorException: 404 Not Found

#RequestMapping(method = RequestMethod.POST, produces = {
MediaType.APPLICATION_JSON_VALUE })
public #ResponseBody String provisionUser(#RequestBody(required = true) String body) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("key", "<key>");
HttpEntity<String> request = new HttpEntity<String>(body, headers);
String APIendpoint = "https://apiendpont.com/provision";
String obj = restTemplate.postForObject(APIendpoint, request, String.class);
return obj;
}
the restTemplate.postForObject() line in the above method is returning
org.springframework.web.client.HttpClientErrorException: 404 Not Found
I have tested the uri, and the header information in a REST client and receive a response - so I know that is the correct url.
I ran this in debug mode and the exception is thrown in RestTemplate.doExecute
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor) throws RestClientException {
Assert.notNull(url, "'url' must not be null");
Assert.notNull(method, "'method' must not be null");
ClientHttpResponse response = null;
try {
ClientHttpRequest request = createRequest(url, method);
if (requestCallback != null) {
requestCallback.doWithRequest(request);
}
response = request.execute();
if (!getErrorHandler().hasError(response)) {
logResponseStatus(method, url, response);
}
else {
handleResponseError(method, url, response);
}
if (responseExtractor != null) {
return responseExtractor.extractData(response);
}
else {
return null;
}
}
catch (IOException ex) {
throw new ResourceAccessException("I/O error on " + method.name() +
" request for \"" + url + "\":" + ex.getMessage(), ex);
}
finally {
if (response != null) {
response.close();
}
}
}
Any ideas on what's going on? Thanks.

Request & Response Windows Phone

I need to send request to server appending xml data as below to the url of the server
<User>
<MobileNumber>xxxxxxxxxx</MobileNumber>
<UserAgent>yyyyy</UserAgent>
</User>
I will get back response as follows
<User>
<MobileNumber>xxxxxxxxxx</MobileNumber>
<ModelId>zzzzzz</ModelId>
<AuthKey>aaaaaaaaa</AuthKey>
<UserAgent>yyyyy</UserAgent>
</User>
I want to parse the recieved xml data
What is the proper way to do this in Windows Phone(7)? first request the url with xml and then receive xml
I am new to windows phone development
what classes should be used??
I am very confused in -
WebClient
WebRequest
WebResponse
HttpWebRequest
HttpWebResponse
Edit: I tried the following code to send request, how do I receive the response??
private void Upload()
{
WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var uri = new Uri("xxxxxxxxxx", UriKind.Absolute);
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "MobileNumber", HttpUtility.UrlEncode("yyyyyyyyy"));
postData.AppendFormat("&{0}={1}", "UserAgent", HttpUtility.UrlEncode("WP7"));
webClient.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
webClient.UploadProgressChanged += webClient_UploadProgressChanged;
webClient.UploadStringAsync(uri, "POST", postData.ToString());
}
Try the following steps
Step 1: add the namespace using System.Net;
Step 2:
public void Upload()
{
WebRequest webRequest;
webRequest = WebRequest.Create(Url + Mobile_No + Request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.BeginGetRequestStream(newAsyncCallback(GetRequestStreamCallback), webRequest);
}
Step 3:
public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
string postData = "Test";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
Step 4 :
public void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
if (Response == "")
{
//show some error msg to the user
}
else
{
//Your response will be available in "Response"
}
}
catch (WebException)
{
//error
}
}
Check this now

Resources