I have the following code:
try {
URL url = new URL(webPage);
try {
is = new FileInputStream(new File("testfiles/test.html"));
byte[] buffer = new byte[is.available()];
int tb = is.read(buffer);
System.out.println(tb);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setDoOutput(true);
con.setRequestProperty(authorizationHeaderName, authorizationHeaderValue);
con.setRequestMethod("POST");
con.setRequestProperty("ACCEPT", "application/hal+json");
OutputStream os = con.getOutputStream();
System.out.println(os);
System.out.println(is);
int bytesCopied = IOUtils.copy(is, os);
os.close();
is.close();
But when I copy my fileInputStream into the OutputStream it comes up with 0 bytes. I checked the size of my output from con.getOutputStream(); and it appears there is no object there. The System.out.println is coming back blank - is there a way to get an outputstream on the httpsUrlConnection class?
From what I know you need to use methods like .read() to read from your file and .write()to write to the other file path.
Related
My Android app has a Webview to access to my website. I noticed in the server that when a file is downloaded by the app the bandwidth used is less than when is downloaded by another device or browser.
In method onDownloadStart I call to an AsyncTask class:
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
//Getting directory to store the file
//Connection handler
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
//Obtaining filename
File outputFile = new File(directory, filename);
InputStream input = new BufferedInputStream(connection.getInputStream());
OutputStream output = new FileOutputStream(outputFile);
byte buffer[] = new byte[1024];
int bufferLength = 0;
int total = 0;
while ((bufferLength=input.read(buffer))!=-1) {
total += bufferLength;
output.write(buffer, 0, bufferLength);
}
connection.disconnect();
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Files downloaded are empty altough their filename and format are correct and I receive HTTP 200 message from the server; also execution does not enter into the while loop. I have tried to change buffer size and the problem is not solved.
I am trying to Post a .txt file to a local tomcat webserver that i have on my system.
But when i try to do a post then i get a Error: Not Found.
The source file is present but even after that i get this error.
Can you please let me know what i am doing wrong here. i have pasted my code below.
File file = new File("C:\\xyz\\test.txt");
URL url = new URL("http://localhost:8080/process/files");
urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
urlconnection.setRequestMethod("POST");
BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int i; // read byte by byte until end of stream
while ((i = bis.read()) >0) {
bos.write(i);
}
bos.close();
System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());
} catch(Exception ae)
{
ae.printStackTrace();
}
try {
InputStream inputStream;
int responseCode=((HttpURLConnection)urlconnection).getResponseCode();
if ((responseCode>= 200) &&(responseCode<=202) ) {
inputStream = ((HttpURLConnection)urlconnection).getInputStream();
int j;
while ((j = inputStream.read()) >0) {
System.out.println("------ TESTING ------");
}
} else {
inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
}
((HttpURLConnection)urlconnection).disconnect();
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
}
Can you please let me know what is going wrong here.
I am scratching my head on this for a long time now.
Thanks
Vikeng
The URL you are POSTing to needs to point to a servlet or something similar. You cannot upload a file to a directory just by sending a POST request--the POST request has to be handled by something.
I use HttpUrlConnection to post outside a json but seems Chinese characters are changing to ?????
I tried with different encoding style like utf-16,big 5 but I cant understand what is causing this.
When I debug this, I can see chineese character before post, but when post, it changes why?
code parts is in the below
String postData,String charset) throws MalformedURLException, IOException{
URL url = new URL(targetUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(
Proxy.NO_PROXY);
connection.setConnectTimeout(postTimeout);
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
contentType+"; charset="+charset);//+charset.getName().toUpperCase());//+charset.getName());
sleep(sleepTime);
OutputStream os = connection.getOutputStream();
//"UnicodeBigUnmarked"
//
// byte[] bt= postData.getBytes();
// System.out.println(bt);
// os.write(bt);
// System.out.println();
// os.flush();
//System.out.println(postData);
try
{
Writer writer = new OutputStreamWriter(os, charset);
writer.write(postData);
writer.flush();
writer.close();
} catch (IOException e) {
logger.severe("Http POST exception");
} finally {
if (os != null) {
os.close();
}
}
int responseCode = connection.getResponseCode();
connection.disconnect();
return responseCode;
I tried with big5,utf-16, but still no change.
Thanks.
I believe that you should use the unicode ascii-safe representation in JSon like explained here
This is the method I have in my java application. It is reading the bytes correctly, I have logged to see if it was. The problem is that the php is not realizing the data is there. I have tested and the .php reads that $_POST is set, but is empty.
public void screenshot(BufferedImage screenshot) {
try {
ImageIO.write(screenshot, "png",
new File(Environment.getStorageDirectory().toString()
.concat(File.separator + SCRIPT_NAME + ".png")));
HttpURLConnection httpUrlConnection;
OutputStream outputStream;
BufferedInputStream fileInputStream;
BufferedReader serverReader;
int totalBytes;
String response = "";
String serverResponse = "";
String localFileName = Environment.getStorageDirectory().toString()
.concat(File.separator + SCRIPT_NAME + ".png");
// Establish a connection
httpUrlConnection = (HttpURLConnection) new URL(
"http://www.scripted.it/scriptoptions/utils/saveScreenshot.php?user="
+ SupraCrafter.statHandler.getUser())
.openConnection();
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
outputStream = httpUrlConnection.getOutputStream();
// Buffered input stream
fileInputStream = new BufferedInputStream(new FileInputStream(
localFileName));
// Get the size of the image
totalBytes = fileInputStream.available();
// Loop through the files data
for (int i = 0; i < totalBytes; i++) {
// Write the data to the output stream
outputStream.write(fileInputStream.read());
}
// Close the output stream
outputStream.close();
// New reader to get server response
serverReader = new BufferedReader(new InputStreamReader(
httpUrlConnection.getInputStream()));
// Read the servers response
serverResponse = "";
while ((response = serverReader.readLine()) != null) {
serverResponse = serverResponse + response;
}
System.out.println(serverResponse);
// Close the buffered reader
serverReader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
URL url = new URL(
"http://scripted.it/scriptoptions/utils/setScreenshotStatus.php?user="
+ SupraCrafter.statHandler.getUser() + "&pass="
+ SupraCrafter.statHandler.getPass() + "&script="
+ SCRIPT_NAME + "&status=1");
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
Here is the .php file:
<?
// Config
$uploadBase = "../screenshots/";
$uploadFilename = $_GET['user'] . ".png";
$uploadPath = $uploadBase . $uploadFilename;
// Upload directory
if(!is_dir($uploadBase))
mkdir($uploadBase);
// Grab the data
$incomingData = file_get_contents('php://input');
// Valid data?
if(!$incomingData)
die("No input data");
// Write to disk
$fh = fopen($uploadPath, 'w') or die("Error opening file");
fwrite($fh, $incomingData) or die("Error writing to file");
fclose($fh) or die("Error closing file");
echo "Success";
?>
It always echos 'no input data.'
You are not encoding the content with application/x-www-form-urlencoded. You should not simply copy the bytes into the HTTP payload, but instead encode it correctly.
application/x-www-form-urlencoded is not the only possible way of encoding it, multipart/form-data is another common choice. Both are supported by almost all webservers, and as a consequence by PHP.
A tutorial on how to encode using Java is here : http://www.devx.com/Java/Article/17679
Why don't you use Apache's HttpClient or similar library that already do that tedious work for you?
Apache HttpClient : http://hc.apache.org/httpcomponents-client-ga/
I want to make a POST by using HttpURLConnection.
I am trying this in 2 ways, but I always get an excetion when doing: conn.getOutputStream();
The exception I get in both cases is:
java.net.SocketException: Operation timed out: connect:could be due to
invalid address
function1:
public void makePost(String title, String comment, File file) {
try {
URL servlet = new URL("http://" + "www.server.com/daten/web/test/testupload.nsf/upload?CreateDocument");
HttpURLConnection conn=(HttpURLConnection)servlet.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
String boundary = "---------------------------7d226f700d0";
conn.setRequestProperty("Content-type","multipart/form-data; boundary=" + boundary);
//conn.setRequestProperty("Referer", "http://127.0.0.1/index.jsp");
conn.setRequestProperty("Cache-Control", "no-cache");
OutputStream os = conn.getOutputStream(); //exception throws here!
DataOutputStream out = new DataOutputStream(os);
out.writeBytes("--" + boundary + "\r\n");
writeParam(INPUT_TITLE, title, out, boundary);
writeParam(INPUT_COMMENT, comment, out, boundary);
writeFile(INPUT_FILE, file.getName(), out, boundary);
out.flush();
out.close();
InputStream stream = conn.getInputStream();
BufferedInputStream in = new BufferedInputStream(stream);
int i = 0;
while ((i = in.read()) != -1) {
System.out.write(i);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
or function 2:
public void makePost2(String title, String comment, File file) {
File binaryFile = file;
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
URLConnection connection = null;
try {
connection = new URL("http://" + "www.server.com/daten/web/test/testupload.nsf/upload?CreateDocument").openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
OutputStream output = connection.getOutputStream(); //exception throws here
writer = new PrintWriter(new OutputStreamWriter(output, CHARSET), true); // true = autoFlush, important!
// Send normal param.
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\""+ INPUT_TITLE +"\"");
writer.println("Content-Type: text/plain; charset=" + CHARSET);
writer.println();
writer.println(title);
// Send binary file.
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\""+ INPUT_FILE +"\"; filename=\"" + binaryFile.getName() + "\"");
writer.println("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()));
writer.println("Content-Transfer-Encoding: binary");
writer.println();
InputStream input = null;
try {
input = new FileInputStream(binaryFile);
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
output.flush(); // Important! Output cannot be closed. Close of writer will close output as well.
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
writer.println(); // Important! Indicates end of binary boundary.
// End of multipart/form-data.
writer.println("--" + boundary + "--");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) writer.close();
}
}
The URL simply cannot be reached. Either the URL is wrong, or the DNS server couldn't resolve the hostname. Try a simple connect with a well-known URL to exclude one and other, e.g.
InputStream response = new URL("http://stackoverflow.com").openStream();
// Consume response.
Update as per the comments, you're required to use a proxy server for HTTP connections. You need to configure that in the Java side as well. Add the following lines before any attempt to connect to an URL.
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
It suffices to do this only once during runtime.
See also:
Java guides - Networking and proxies
Without establishing the connection (which in this case requires 1 more step to be performed ie connect), transfer is not possible. connect() should be called after the connection is configured (ie after being done with the set***() on the connection).
What is missing is:
conn.connect();