I need to download a image files from the file system using RESTEasy web service and the input httpclient is JSON and the output response is
#Produces({"image/jpeg,image/png"})
Here is my client code:
public void getFileDownload(){
log("inside getServerPath....");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(downloadWebService_URL);
JSONObject json = new JSONObject();
json.put("filePath", "/ngs/app/sample.png");
json.put("fileName", "sample.png");
log("json-->"+json.toString());
StringEntity inputJson = null;
try {
inputJson = new StringEntity(json.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
log("inputJson = " + inputJson.toString());
inputJson.setContentType("application/json");
httpPost.setEntity(inputJson);
httpPost.addHeader("AppType", "TC");
log("httpPost... httpPost");
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
log("response:-->"+response);
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e)
{
log("E:: " + ExceptionUtils.getStackTrace(e));
}
}
Here is my Webservice code:
#Path("/downloadservice")
public class DownloadFileWS {
private static final String FILE_PATH = "/ngs/app/sample.png";
#POST
// #Path("/images")
#Path("/{fileName}/images")
#Consumes({"application/json"})
#Produces({"image/jpeg,image/png"})
public Response getImageFile(#PathParam("fileName") String fileName) {
File file = new File(FILE_PATH);
System.out.println("File requested is : " + fileName);
Logger.getLogger("!!!!!!!!!!!"+FILE_PATH);
System.out.println("########"+FILE_PATH);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition","attachment; filename=\"sample.png\"");
return response.build();
}
The HTTP Response is:
response:-->HTTP/1.1 200 OK [Date: Tue, 19 Jul 2016 00:36:22 GMT,
Content-Length: 6192, Content-Type: image/png, Content-Disposition:
attachment; filename="sample.png", X-Powered-By: Servlet/2.5 JSP/2.1]
org.apache.http.conn.BasicManagedEntity#2ace1307
Question:
1. Based on the response, it looks like the service is sending the image in HTTPResponse object. May i know how to download the image received from HTTP Response?
2. The requirement is to click a link which calls the webservice by passing JSON as input request and the image should automatically download to the user's local machine browser.
Related
I am trying to get the response from webservice- http://services.groupkt.com/state/get/IND/all .It is working fine normally through java code but when I have deployed in google app engine it is returning 500 error.
Following one is the code.
try {
// create HTTP Client
HttpClient httpClient = HttpClientBuilder.create().build();
// Create new getRequest with below mentioned URL
HttpGet getRequest = new HttpGet("http://services.groupkt.com/state/get/IND/all");
// Add additional header to getRequest which accepts application/xml data
getRequest.addHeader("accept", "application/json");
// Execute your request and catch response
HttpResponse response = httpClient.execute(getRequest);
// Check for HTTP response code: 200 = success
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
// Get-Capture Complete application/xml body response
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("============Output:============");
// Simply iterate through XML response and show on console.
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I have searched it.It is showing as internal server error.How can i fix it?
I am trying to send an XML soap request to a dynamics nav web service. This is the XML from the WSDL. I have created a web access key and its the one in the key parameter of the XML.
<s11:Envelope xmlns:s11='http://schemas.xmlsoap.org/soap/envelope/'>
<s11:Body>
<ns1:Create xmlns:ns1='urn:microsoft-dynamics-schemas/page/customerws'>
<ns1:CustomerWS>
<ns1:Key>+gn8Nu4i7iW7D/g9vCaI8HZE5IEi1NBkTBqDp5QfXe4=</ns1:Key>
<ns1:Shipping_Advice></ns1:Shipping_Advice>
<ns1:Shipment_Method_Code></ns1:Shipment_Method_Code>
<ns1:Shipping_Agent_Code></ns1:Shipping_Agent_Code>
<ns1:Shipping_Agent_Service_Code></ns1:Shipping_Agent_Service_Code>
<ns1:Shipping_Time></ns1:Shipping_Time>
<ns1:Base_Calendar_Code></ns1:Base_Calendar_Code>
<ns1:Customized_Calendar></ns1:Customized_Calendar>
<ns1:Currency_Code></ns1:Currency_Code>
<ns1:Language_Code></ns1:Language_Code>
<ns1:VAT_Registration_No></ns1:VAT_Registration_No>
</ns1:CustomerWS>
</ns1:Create>
</s11:Body>
</s11:Envelope>
And this is the code that am using to send this request:
Console.WriteLine("We have started");
string pageName = "http://hrp-dmu.uganda.hrpsolutions.co.ug:9047/DynamicsNAV80/WS/Uganda%20Management%20Institute/Page/CustomerWS";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pageName);
req.Method = "POST";
req.ContentType = "text/xml;charset=UTF-8";
req.ProtocolVersion = new Version(1, 1);
req.Headers.Add("SOAPAction", #"urn:microsoftdynamicsschemas/page/customerws:Create");
Console.WriteLine("After preparing request object");
string xmlRequest = GetTextFromXMLFile("E:\\tst3.xml");
Console.WriteLine("xml request : "+xmlRequest);
byte[] reqBytes = new UTF8Encoding().GetBytes(xmlRequest);
req.ContentLength = reqBytes.Length;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(reqBytes, 0, reqBytes.Length);
}
}
catch (Exception ex)
{
Console.WriteLine("GetRequestStreamException : " + ex.Message);
}
HttpWebResponse resp = null;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (Exception exc)
{
Console.WriteLine("GetResponseException : " + exc.Message);
}
string xmlResponse = null;
if (resp == null)
{
Console.WriteLine("Null response");
}
else
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
xmlResponse = sr.ReadToEnd();
}
Console.WriteLine("The response");
Console.WriteLine(xmlResponse);
}
Console.ReadKey();
when using NavUserPassword Authentication you'll need a certificate.
See here on MSDN
Cheers!
How can i respond back with a text file containing json data upon request from client .
The request url is:
http://localhost:8082/web/ws/datafileid/json/Sat May 16 12:05:07 IST 2015.txt/
Controller code that handles the request is:
#RequestMapping(value=EmpRestURIConstants.DATAFILE_REQUEST,method=RequestMethod.GET)
#ResponseBody
public String datafileresponse(#PathVariable("filename") String filename, HttpServletResponse response) {
return cinehomeRestService.checkfilevalid(filename);
}
Service class that handles the request to check the file exists is:
#Override
public String checkfilevalid(String filename) {
String datafilename=webServiceDao.getdatafilename();
JSONObject obj = new JSONObject();
if(datafilename.equals(filename)) {
return "file";
}
else {
try {
obj.put("status", "022");
} catch (JSONException e) {
e.printStackTrace();
}
return obj.toString();
}
}
Here I need to respond back with the datafile.txt that exists at location resources. How can I perform the task. Can anyone help?
i have tried a method
#RequestMapping(value=EmpRestURIConstants.DATAFILE_REQUEST,method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody Response datafileresponse(#PathVariable("filename")String filename) throws IOException{
JSONObject readdata = new JSONObject();
String uploadPath = servletContext.getRealPath("");
String fullyqualifiedfilename=uploadPath+filename;
System.out.println("+++++++++"+fullyqualifiedfilename);
return Response.ok(uploadPath)
.header("Content-Disposition", "attachment; filename=\"" + fullyqualifiedfilename + "\"" ) //optional
.build();
}
i GOT THE REPLY AS...
{ "statusType": "OK", "entity": /home/cine/WORKSPACES/study/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/
"entityType": "java.lang.String", "metadata": { "Content-Disposition": [ "attachment;
filename="/home/cine/WORKSPACES/study/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Cine Sat May 16 12:05:07 IST 2015.txt"" ] }, "status": 200 }
What this status means. Does the client can fetch teh file using this response.??
I've got this below restful webservice code. But when the webservice is accessed I'm getting "MIME media type application/pdf was not found". The docService.findByVersionId does return a "TestDoc" which holds the pdf content as byte[].
Can you please help me in fixing this problem?
#GET
#Path("/getPdf/{versionId}")
#Produces("application/pdf")
public Response getPdfFile(#PathParam("versionId") final String versionId) {
try {
final TestDoc doc = this.docService.findByVersionId(versionId);
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final BufferedOutputStream bos = new BufferedOutputStream(byteArrayOutputStream);
final byte[] pdfContent = doc.getPdfDoc();
bos.write(pdfContent);
bos.flush();
bos.close();
return Response.ok(byteArrayOutputStream).build();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
error:
Exception:
2014-01-02 12:42:07,497 ERROR [STDERR] 02-Jan-2014 12:42:07 com.sun.jersey.spi.container.ContainerResponse write
SEVERE: A message body writer for Java class java.io.ByteArrayOutputStream, and Java type class java.io.ByteArrayOutputStream, and MIME media type application/pdf was not found
It seems that you can't use the ByteArrayOutputStream. The solution is to use StreamingOutput.
#GET
public Response generatePDF(String content) {
try {
ByteArrayOutputStream outputStream = service.generatePDF(content);
StreamingOutput streamingOutput = getStreamingOutput(outputStream);
Response.ResponseBuilder responseBuilder = Response.ok(streamingOutput, "application/pdf");
responseBuilder.header("Content-Disposition", "attachment; filename=Filename.pdf");
return responseBuilder.build();
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
return Response.serverError().build();
}
}
private StreamingOutput getStreamingOutput(final ByteArrayOutputStream byteArrayOutputStream) {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
byteArrayOutputStream.writeTo(output);
}
};
}
I am trying to use N-UNIT to test my web API application but I am unable to find a proper way to test my file upload method. Which would be the best approach to test the method?
Web API Controller:
[AcceptVerbs("post")]
public async Task<HttpResponseMessage> Validate()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
return Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType,"please submit a valid request");
}
var provider = new MultipartMemoryStreamProvider(); // this loads the file into memory for later on processing
try
{
await Request.Content.ReadAsMultipartAsync(provider);
var resp = new HttpResponseMessage(HttpStatusCode.OK);
foreach (var item in provider.Contents)
{
if (item.Headers.ContentDisposition.FileName != null)
{
Stream stream = item.ReadAsStreamAsync().Result;
// do some stuff and return response
resp.Content = new StringContent(result, Encoding.UTF8, "application/xml"); //text/plain "application/xml"
return resp;
}
}
return resp;
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
Based on your above comment, following is an example:
HttpClient client = new HttpClient();
MultipartFormDataContent formDataContent = new MultipartFormDataContent();
formDataContent.Add(new StringContent("Hello World!"),name: "greeting");
StreamContent file1 = new StreamContent(File.OpenRead(#"C:\Images\Image1.jpeg"));
file1.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
file1.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
file1.Headers.ContentDisposition.FileName = "Image1.jpeg";
formDataContent.Add(file1);
StreamContent file2 = new StreamContent(File.OpenRead(#"C:\Images\Image2.jpeg"));
file2.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
file2.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
file2.Headers.ContentDisposition.FileName = "Image1.jpeg";
formDataContent.Add(file2);
HttpResponseMessage response = client.PostAsync("http://loclhost:9095/api/fileuploads", formDataContent).Result;
The request over the wire would like:
POST http://localhost:9095/api/fileuploads HTTP/1.1
Content-Type: multipart/form-data; boundary="34d56c28-919b-42ab-8462-076b400bd03f"
Host: localhost:9095
Content-Length: 486
Expect: 100-continue
Connection: Keep-Alive
--34d56c28-919b-42ab-8462-076b400bd03f
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=greeting
Hello World!
--34d56c28-919b-42ab-8462-076b400bd03f
Content-Type: image/jpeg
Content-Disposition: form-data; filename=Image1.jpeg
----Your Image here-------
--34d56c28-919b-42ab-8462-076b400bd03f
Content-Type: image/jpeg
Content-Disposition: form-data; filename=Image2.jpeg
----Your Image here-------
--34d56c28-919b-42ab-8462-076b400bd03f--
After spending a bit of time looking into WebClient I was able to come up with this:
try
{
var imageFile = Path.Combine("dir", "fileName");
WebClient webClient = new WebClient();
byte[] rawResponse = webClient.UploadFile(string.Format("{0}/api/values/", "http://localhost:12345/"), imageFile);
Console.WriteLine("Sever Response: {0}", System.Text.Encoding.ASCII.GetString(rawResponse)); // for debugging purposes
Console.WriteLine("File Upload was successful");
}
catch (WebException wexc)
{
Console.WriteLine("Failed with an exception of " + wexc.Message);
// anything other than 200 will trigger the WebException
}