How can I get image files by URLConnection.getOutputStream() method? - java

There is an ASP.NET web page to encode some images and save them to a specified folder...
I want to call this page by JAVA URL method,
but I don't know how to use getOutputStream() method to save this encoded images....
The following is my unfinished code :
try {
String encodeImgUrl = "XXX.aspx";
InputStream is = null;
URL url = new URL(encodeImgUrl);
is = url.openStream();
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
// .... I don't know how to use connection.getOutputStream() to save this encoded images....
is.close();
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}

Related

Java simple update method

So i have this simple method to download and replace a file:
public void checkForUpdates() {
try {
URL website = new URL(downloadFrom);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(downloadTo);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
} catch (IOException e) {
System.out.println("No files found");
}
}
How can i check if there is a concrete file with a certain name located in the destination (downloadFrom) ? Right now if there are no files it downloads the html page.
You can get content type from header
URL url = new URL(urlname);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
String contentType = connection.getContentType();
then check it's HTML/text or files.
I suggest to check the HTTP code for code 200. Something along these lines:
public class DownloadCheck {
public static void main(String[] args) throws IOException {
System.out.println(hasDownload("http://www.google.com"));
System.out.println(hasDownload("http://www.google.com/bananas"));
}
private static boolean hasDownload(String downloadFrom) throws IOException {
URL website = new URL(downloadFrom);
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) website.openConnection();
return connection.getResponseCode() == 200; // You could check other codes though
}
catch (Exception e) {
Logger.getLogger(OffersUrlChecker.class.getName()).log(Level.SEVERE,
String.format("Could not read from %s", downloadFrom), e);
return false;
}
finally {
if (connection != null) {
connection.disconnect(); // Make sure you close the sockets
}
}
}
}
If you run this code, you will get:
true
false
as the output.
You could consider to consider other code than code 200 as OK. See more information on HTTP codes here.

Calling php script from java - Android

I have the following copyfile.php file inside my main directory with the below code :
<?php
copy("dir1/test.php","dir2/test.php");
?>
Basically just moving a file from dir1 to dir2 (both the directories are already created and are present in my main directory)
I am using the following java code to call my copyfile.php
try {
URL url;
url = new URL( "http://www.xyz.com/copyfile.php" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
InputStream is = conn.getInputStream();
// do something with the data here
}else{
InputStream err = conn.getErrorStream();
// err may have useful information.. but could be null see javadocs for more information
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
The program runs without any errors but the file is not being copied.
But if I paste the above url (http://www.xyz.com/copyfile.php) in the browser it works fine the file gets copied to dir2. Am I doing something wrong? Please help. Thanks in advance :)

Login to a website (Java)

I want to login to a website, but if I try it with this code:
package URL;
//Variables to hold the URL object and its connection to that URL.
import java.net.*;
import java.io.*;
public class URLLogin {
private static URL URLObj;
private static URLConnection connect;
public static void main(String[] args) {
try {
// Establish a URL and open a connection to it. Set it to output mode.
URLObj = new URL("http://login.szn.cz");
connect = URLObj.openConnection();
connect.setDoOutput(true);
}
catch (MalformedURLException ex) {
System.out.println("The URL specified was unable to be parsed or uses an invalid protocol. Please try again.");
System.exit(1);
}
catch (Exception ex) {
System.out.println("An exception occurred. " + ex.getMessage());
System.exit(1);
}
try {
// Create a buffered writer to the URLConnection's output stream and write our forms parameters.
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream(),"UTF-8"));
writer.write("username=S&password=s&login=Přihlásit se");
writer.close();
// Now establish a buffered reader to read the URLConnection's input stream.
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String lineRead = "";
Read all available lines of data from the URL and print them to screen.
while ((lineRead = reader.readLine()) != null) {
System.out.println(lineRead);
}
reader.close();
}
catch (Exception ex) {
System.out.println("There was an error reading or writing to the URL: " + ex.getMessage());
}
}
}
I get this error:
There was an error reading or writing to the URL: Server returned HTTP
response code: 405 for URL: http://login.szn.cz
Is here a way how I can login to this website? Or maybe I can use cookies in Opera browser with login information?
Thanks for all advices.
You can call the URL object's openConnection method to get a URLConnection object. You can use this URLConnection object to setup parameters and general request properties that you may need before connecting. Connection to the remote object represented by the URL is only initiated when the URLConnection.connect method is called. The following code opens a connection to the site example.com:
try {
URL myURL = new URL("http://login.szn.cz");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
catch (IOException e) {
// openConnection() failed
// ...
}
A new URLConnection object is created every time by calling the openConnection method of the protocol handler for this URL.
Also see these links..
http://www.coderanch.com/t/524061/open-source/Java-program-Login-website-url
Login on website with java

Problems displaying PDF inside a new browser tab using a flex + servlet + jasper

I'm using my reportService class to generate the JasperPrint object that contains my report, then I send it to a Servlet and it generates the PDF. The problem is that this servlet is not opening the PDF in a new tab(this is what I want), actually it doesn't even prompting me to download it or anything.
Servlet Caller:
try {
URL url = new URL("http://" + serverName + ":" + serverPort + path
+ "/reportgenerator");
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setDefaultUseCaches(false);
connection.setRequestProperty("Content-Type",
"application/octet-stream");
ObjectOutputStream out = new ObjectOutputStream(
connection.getOutputStream());
//This "jasperPrint" is my generated report from my service
out.writeObject(jasperPrint);
out.close();
connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
My doPost method from my Servlet:
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JasperPrint jasperPrint = null;
ObjectInputStream resultStream = null;
ServletOutputStream out = response.getOutputStream();
try {
resultStream = new ObjectInputStream(request.getInputStream());
jasperPrint = (JasperPrint) resultStream.readObject();
resultStream.close();
byte[] rel = JasperExportManager.exportReportToPdf(jasperPrint);
out.write(rel,0, rel.length);
//JasperExportManager.exportReportToPdfStream(jasperPrint, out);
response.setContentLength(rel.length);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition",
"attachment; filename=\"report.pdf\"");
response.setHeader("Cache-Control", "no-cache");
System.err.println(rel.length);
} catch (JRException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
out.flush();
out.close();
}
}
What am I doing wrong?
Assuming you have the byte[] of the file you want to open on the flex side of your application you should be able to write the file to a temp location and then open it. It would look similar to this:
//create a temp dir in the system temp directory to place all the temp files for you app.
private static var tempDir:File=File.createTempDirectory();
/**
* bytes - the byte array of the pdf you want to open
* filename - the name to use for the temp file, you may need to create some type of
* counter to add to the beginning of the filename so that you always get
* a unique name
*/
public static openFile(bytes:ByteArray,filename:String):void{
//create a file in the system temp directory to write the file to
var tempFile:File = tempDir.resolvePath(filename);
//create a filestream to write the byte array to the file
var fileStream:FileStream = new FileStream();
fileStream.open(tempFile, FileMode.WRITE);
fileStream.writeBytes(bytes,0,bytes.length);
fileStream.close();
//open the temp file with default application
tempFile.openWithDefaultApplication();
}
I've solved my problem returning the JasperPrint as a byte[] to my flex application, in flex it will be treated as a ByteArray(because it's converted by, in my case, graniteds) and then I just call my servlet sending this ByteArray.
I'm looking for another solution, but it can help someone else.

Twitter request with java connection fails

I can pull the user's statuses with no problem with cURL, but when I connect with Java, the xml comes out truncated and my parser wants to cry. I'm testing with small users so it's not choke data or anything.
public void getRuserHx(){
System.out.println("Getting user status history...");
String https_url = "https://twitter.com/statuses/user_timeline/" + idS.rootUser + ".xml?count=100&page=[1-32]";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(15*1000);
//dump all the content into an xml file
print_content(con);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished downloading user status history.");
}
private void print_content(HttpsURLConnection con){
if(con!=null){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
File userHx = new File("/" + idS.rootUser + "Hx.xml");
PrintWriter out = new PrintWriter(idS.hoopoeData + userHx);
String input;
while ((input = br.readLine()) != null){
out.println(input);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
This request doesn't need auth. Sorry about my ugly code. My professor says input doesn't matter so my I/O is a trainwreck.
You have to flush the output stream when you write the content out. Did you flush or close the output stream?

Categories

Resources