Download attachment file from URL - JAVA - java

I am trying to download a file from a URL like below.
http://localhost/attachment.php?attachId=123
It was downloading as a PHP file instead of the attachment. I have tried like this.
url = new URL(sourceURL);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.addRequestProperty("User-Agent", "Mozilla/4.76");
if(httpcon.getResponseCode()!=404){
InputStream is = httpcon.getInputStream();
Files.copy(is, Paths.get(destinationFile));
}

Related

HTTPURLConnection write command works only with read

I am writing a file into AWS S3 bucket using HTTPURLConnection. This connection's outputstream-write command works only if it is followed by getInputStream or getResponseCode. Please help me to understand this. Is it required to read responseCode?
URL endpointUrl = new URL("muURL");
HttpURLConnection connection = (HttpURLConnection) endpointUrl.openConnection();
connection.setRequestMethod("PUT");
connection.setRequestProperty("Authorization", authorization);
connection.setRequestProperty("x-amz-content-sha256", hashPayload);
connection.setRequestProperty("X-Amz-Date", myDate);
connection.setRequestProperty("Content-Type","application/octet-stream");
connection.setRequestProperty("Content-Length",contentLen);
//connection.setRequestProperty("Accept","*/*");
connection.setUseCaches(false);
//connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(payload);
StringBuilder builder = new StringBuilder();
// If I comment this line which gets responseCode , then file is not written in S3.
builder.append(connection.getResponseCode());
wr.flush();
wr.close();
connection.disconnect();
I am expecting this code to work without getResponseCode line.

Unable to post file in Python [Working in Java]

I'm quite new to Python and I've been trying to make a post request in Python by sending an xml file along with the request. In Java I could perfectly do it with the below piece of code
String url = "https://www.test.com"
URL object = new URL(url);
HttpURLConnection conn = (HttpURLConnection) object.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Accept", "application/xml");
conn.setRequestMethod("POST");
BufferedReader br = new BufferedReader((new FileReader("D:\\test.xml")));
String line1;
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
while ((line1 = br.readLine()) != null) {
wr.write(line1);
}
wr.flush();
wr.close();
int HttpResult = conn.getResponseCode();
To make it work in Python, I've tried different ways. None of them worked
headers = {"Content-type": "application/xml",
"Accept": "application/xml",
}
url = "https://www.test.com"
filePath = "D:\\test.xml"
file_data = [('file', (filePath, open(filePath), 'application/xml'))]
resp = requests.post(url = url, files=file_data, headers=headers)
print("resp=",resp.url)
print("resp=",resp)
And few other options as well
files = {'file':(filePath, open(filePath, 'rb'))}
files = {'file': (filePath, open(filePath, 'rb'), 'application/xml', {'Accept': 'application/xml'})}
Even I tried to send the file as data. But to no avail.
data = open("D:\\test.xml", 'rb').read()
resp = requests.post(url = url, data=data, headers=headers)
Please help me to understand where I'm Wrong. I've been breaking my head for hours.
FYI: I'm using Python 3.6.1
Looking at the official documentation of requests, I can find this example (adapted to your case):
url = "https://www.test.com"
filePath = "D:\\test.xml"
files = {'file': (filePath, open(filePath, 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)
The original quickstart example is here:
https://requests.readthedocs.io/en/master/user/quickstart/#post-a-multipart-encoded-file

Send file from Action to Servlet

My goal is to upload a file from an action to a servlet.
Till now, I thought I had it working in this way:
Action: reads file as bytearray, converts it into String and puts String on request
HttpURLConnection conn =null;
String url = "http://myServlet");
URL obj = new URL(url);
conn = (HttpURLConnection) obj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
StringBuffer requestParams = new StringBuffer();
requestParams.append("fileString");
requestParams.append("=").append(URLEncoder.encode(fileString, "ISO-8859-1"));
//Append more params
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(requestParams.toString());
wr.flush();
conn.getContentLength();
Servlet: get String parameter, converts it back to bytearray and re-creates the file
receivedString = request.getParameter("fileString");
//Convert to bytearray and create file
But I guess this isn't a good solution, cause sometimes the call just fails because of the string (length maybe?)
Which is the right way to send my file? I can't find a way to send the file AND additional informations putting them on the request.

How to get redirected URL and content using HttpURLConnection

Sometimes my URL will redirect to a new page, so I want to get the URL of the new page.
Here is my code:
URL url = new URL("http://stackoverflow.com/questions/88326/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(true);
System.out.println(conn.getURL().toString());
The output is:
stackoverflow.com/questions/88326/does-elmah-handle-caught-exceptions-as-well
It works well for the Stack Overflow website, but for the sears.com site, it doesn't work.
If we enter the URL blow:
http://www.sears.com/search=iphone
the output is still:
http://www.sears.com/search=iphone
But actually, the page will redirect to:
http://www.sears.com/tvs-electronics-phones-all-cell-phones/s-1231477012?keyword=iphone&autoRedirect=true&viewItems=25&redirectType=CAT_REC_PRED
How can I solve this problem?
Simply call getUrl() on URLConnection instance after calling getInputStream():
URLConnection con = new URL(url).openConnection();
System.out.println("Orignal URL: " + con.getURL());
con.connect();
System.out.println("Connected URL: " + con.getURL());
InputStream is = con.getInputStream();
System.out.println("Redirected URL: " + con.getURL());
is.close();
If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:
HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
con.setInstanceFollowRedirects(false);
con.connect();
int responseCode = con.getResponseCode();
System.out.println(responseCode);
String location = con.getHeaderField("Location");
System.out.println(location);
actually we can use HttpClient, which we can set HttpClient.followRedirect(true)
HttpClinent will handle the redirect things.

HttpURLConnection to Tomcat

I am trying to connect from a java desktop application to a jsp Servlet to send a file.
Clientcoding:
HttpURLConnection urlConnection = null;
URL url = null;
url = new URL("http://127.0.0.1:8080/emobile/AddTripMobile");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
OutputStream out = new BufferedOutputStream(
urlConnection.getOutputStream());
out.write(12); //The data to send
out.flush();
If I connect with the desktop application to the server nothing happens.
(I set a breakpoint in the doGet and doPost)
Any suggestions?
You need to add the following :
InputStream is = urlConnection.getInputStream();
out.write(12); //The data to send
out.flush();
Try closing the output stream.

Categories