After filling necessary package info, I manage to create a responsed Transaction object through goShippo API call: Transaction.create(Map, apiKey). Form the responsed Transaction object, I can get the shipping label as a Url: transaction.getObjectId().
The problem that I have is how can I enable my client to download the shipping label.
My current code is:
fileName= "https://shippo-delivery-east.s3.amazonaws.com/b1b0e6af.pdf?xxxxxx";
File file = new File(fileName);
String mineType = URLConnection.guessContentTypeFromName(file.getName());
if(mineType == null) {
System.out.println("mineType is not detectable");
mineType = "application/octet-stream";
}
response.setContentType(mineType);
response.setHeader("Content-Disposition"
, String.format("inline; filename=\"" + file.getName() +"\""));
response.setContentLength((int)file.length());
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
FileCopyUtils.copy(inputStream, response.getOutputStream());
The error that I have is that the file is not found, but when I pass the fileName on browser, I can see the shipping label.
The documentation says:
After you've successfully created a URL, you can call the URL's openStream() method to get a stream from which you can read the contents of the URL. The openStream() method returns a java.io.InputStream object, so reading from a URL is as easy as reading from an input stream.
So you need to create a URL object and from it you can get the inputStream.
It looks like this:
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
String fileName= "https://shippo-delivery-east.s3.amazonaws.com/b1b0e6af.pdf?xxxxxx";
URL urlToLabel = new URL(fileName);
InputStream inputStream = new BufferedInputStream(urlToLabel.openStream());
Related
I'm trying to download a file using HTTP, and here is the code.
With this, I have a directory made with a correct name, and a file within the directory made with a correct name, but there is NOTHING WRITTEN in the file.
PostMethod post = new PostMethod(serverUrl);
post.setRequestEntity(entity);
httpclient.executeMethod(post);
File contentDirectory = new File(fileFullPath);
if(contentDirectory.exists() == false){
contentDirectory.mkdir();
}
File localFile = new File(fileFullPath + File.separator + filename);
int readBuf = 0;
byte[] buf = new byte[Utils.getBufferSize()]; (BufferSize Checked)
InputStream is = null;
is = post.getResponseBodyAsStream();
FileOutputStream fos = new FileOutputStream(localFile);
while((readBuf = is.read(buf))!= -1){
fos.write(buf, 0, readBuf);
logger.info("readBuf : "+readBuf);
}
is.close();
fos.close();enter code here
if(localFile.exists()) Transfer_Success = true;
Being a noob I am, turns out all this time I was sending post method to a wrong servlet. A mistake only novices make.
So I have the bytes transferred correctly, but this time the image files can't be open due to wrong encoding type or something. I'm on to resolving this.
Can objects be appended to post requests in Java or do they have to be converted to Strings first? I know for sure they can be sent as a String using the NameValuePair class, but is there a way to send a serializable plain old Java object through a post request? How would I do that?
EDIT: I found an example, but the post request isn't going through... this is my code:
URL url = new URL("http://localhost:8080/test123/User");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true); // to be able to write.
conn.setDoInput(true); // to be able to read.
ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());
out.writeObject(myObj);
out.close();
I'm trying to write a Groovy script that will post a Word (docx) file to a REST handler on my grails application.
The request is constructed like so:
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.mime.MultipartEntity
import org.apache.http.entity.mime.content.FileBody
import org.apache.http.entity.mime.content.StringBody
import org.apache.http.impl.client.DefaultHttpClient
class RestFileUploader {
def sendFile(file, filename) {
def url = 'http://url.of.my.app';
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntity reqEntity = new MultipartEntity();
FileBody bin = new FileBody(file);
reqEntity.addPart("file", new FileBody((File)file, "application/msword"));
def normalizedFilename = filename.replace(" ", "")
reqEntity.addPart("fileName", new StringBody(normalizedFilename));
httppost.setEntity(reqEntity);
httppost.setHeader('X-File-Size', (String)file.size())
httppost.setHeader('X-File-Name', filename)
httppost.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=utf-8')
println "about to post..."
HttpResponse restResponse = httpclient.execute(httppost);
HttpEntity resEntity = restResponse.getEntity();
def responseXml = resEntity.content.text;
println "posted..."
println restResponse
println resEntity
println responseXml.toString()
return responseXml.toString()
}
}
On the receiving controller, I read in the needed headers from the request, and then try to access the file like so:
def inStream = request.getInputStream()
I end up writing out a corrupted Word file, and from examining the file size and the contents, it looks like my controller is writing out the entire request, rather than just the file.
I've also tried this approach:
def filePart = request.getPart('file')
def inStream = filePart.getInputStream()
In this case I end up with an empty input stream and nothing gets written out.
I feel like I'm missing something simple here. What am I doing wrong?
You will need to make two changes:
Remove the line: httppost.setHeader('Content-Type'.... File upload HTTP POST requests must have content type multipart/form-data (set automatically by HttpClient when you construct a multipart HttpPost)
Change the line: reqEntity.addPart("file", ... to: reqEntity.addPart("file", new
FileBody(file)). Or use one of the other non-deprecated FileBody constructors to specify a valid content type and charset (API link) This assumes that your file method parameter is of type java.io.File -- this isn't clear to me from your snippet.
Then, as dmahapatro suggests, you should be able to read the file with: request.getFile('file')
I want to get Inbox via RSS, I can get XML when I use Response.Redirect , but can not get as XML format, it throws (401) unauthorized error My Code is
string url = "https://myusername:mypassword#mail.google.com/mail/feed/atom";
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
reader.Close();
-->Response.redirect(url); //it is working
Can any one have any idea about it,
or
is any verson of AE.Net.Mail.dll for Framework 2.0
Thanks you
The XmlReader class cannot parse authentication information from the URL, you have to create an XmlSettings instance and set its XmlResolver property to an XmlUrlResolver instance that has its credentials set to the username and password. Then when you create the XmlReader instance, you supply the custom XmlSettings instance. The following code would do the trick:
// Create a resolver with your credentials
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = new NetworkCredential("myusername", "mypassword");
// Set the reader settings object to use the resolver.
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = resolver;
string url = "https://mail.google.com/mail/feed/atom";
// Create the reader using the specified URL and settings
XmlReader reader = XmlReader.Create(url, settings);
SyndicationFeed feed = SyndicationFeed.Load(reader);
reader.Close();
However, I tried this code and the following XmlException was thrown:
"The element with name 'feed' and namespace 'http://purl.org/atom/ns#' is not an allowed feed format."
It appears that the feeds Google outputs are in a format that is incompatible with the SyndicationFeed class. For more information see: http://www.eggheadcafe.com/tutorials/csharp/9faa101f-0a1a-465f-a41a-3e52dd9f7526/everything-rss--atom-feed-parser.aspx
I am trying to create a upload servlet that handles enctype="multipart/form-data" from a form. The file I am trying to upload is a zip. However, I can upload and read the file on localhost, but when I upload to the server, I get a "File not found" error when I want to upload a file. Is this due to the Struts framework that I am using? Thanks for your help. Here is part of my code, I am using FileUpload from http://commons.apache.org/fileupload/using.html
I have changed to using ZipInputStream, however, how to I reference to the ZipFile zip without using a local disk address (ie: C://zipfile.zip). zip is null because its not instantiated. I will need to unzip and read the zipentry in memory, without writing to the server.
For the upload servlet:
>
private ZipFile zip;
private CSVReader reader;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List <FileItem> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
//Iterating through the uploaded zip file and reading the content
FileItem item = (FileItem) iter.next();
ZipInputStream input = new ZipInputStream(item.getInputStream());
ZipEntry entry = null;
while (( entry= input.getNextEntry()) != null) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(entry.getName().toString().equals("file.csv")){
//unzip(entry)
}
}
}
public static void unzip(ZipEntry entry){
try{
InputStream inputStream = **zip**.getInputStream(entry);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new CSVReader(inputStreamReader);
}
catch(Exception e){
e.printStackTrace();
}
}
<
Here,
zip = new ZipFile(new File(fileName));
You're assuming that the local disk file system at the server machine already contains the file with exactly the same name as it is at the client side. This is a wrong assumption. That it worked at localhost is obviously because both the webbrowser and webserver "by coincidence" runs at physically the same machine with the same disk file system.
Also, you seem to be using Internet Explorer as browser which incorrectly includes the full path in the filename like C:/full/path/to/file.ext. You shouldn't be relying on this browser specific bug. Other browsers like Firefox correctly sends only the file name like file.ext, which in turn would have caused a failure with new File(fileName) (which should have helped you to spot your mistake much sooner).
To fix this "problem", you need to obtain the file contents as InputStream by item.getInputStream():
ZipInputStream input = new ZipInputStream(item.getInputStream());
// ...
Or to write it to disk by item.write(file) and reference it in ZipFile:
File file = File.createTempFile("temp", ".zip");
item.write(file);
ZipFile zipFile = new ZipFile(file);
// ...
Note: don't forget to check the file extension beforehand, else this may choke.