HTTP POST not working.Getting Not Found error - java

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.

Related

not sure why I am getting an empty outputstream from httpurlconnection

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.

How to download .zip file from URL using java [duplicate]

This question already has answers here:
Download file from server in java
(2 answers)
Closed 4 years ago.
guys!
I have a problem! I'm trying to download a .zip (size is 150 mb) file from Internet using this code:
public void downloadBuild(String srcURL, String destPath, int bufferSize, JTextArea debugConsole) throws FileNotFoundException, IOException {
debugConsole.append(String.format("**********Start process downloading file. URL: %s**********\n", srcURL));
try {
URL url = new URL(srcURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.connect();
in = httpConn.getInputStream();
out = new FileOutputStream(destPath);
byte buffer[] = new byte[bufferSize];
int c = 0;
while ((c = in.read(buffer)) > 0) {
out.write(buffer, 0, c);
}
out.flush();
debugConsole.append(String.format("**********File. has been dowloaded: Save path is: %s********** \n", destPath));
} catch (IOException e) {
debugConsole.append(String.format("**********Error! File was not downloaded. Detail: %s********** \n", e.toString()));
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
}
but the file is not completely downloaded. (only 4000 bytes). What am I doing wrong?
you can use the following code to download and extract zip file from given uri path.
URL url = new URL(uriPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
ZipInputStream zipIn = new ZipInputStream(in);
ZipEntry entry = zipIn.getNextEntry();
while(entry != null) {
System.out.println(entry.getName());
if (!entry.isDirectory()) {
// if the entry is a file, extracts it
System.out.println("===File===");
} else {
System.out.println("===Directory===");
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
FileOutputStream("example.zip").getChannel().transferFrom(Channels.newChannel(new URL("http://www.example.com/example.zip").openStream()), 0, Long.MAX_VALUE);
Simple one-liner. For more info, read here

Android Webview app not downloading successful

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.

How to get VIEWSTATE before posting using HttpURLConnection (android/java)?

I am writing an Android application, and have been looking for a way to get the _VIEWSTATE from the server I want to post to so I can put it in my Http post content. A few people recommended regex, but then some other pros were strongly opposed to parsing HTML with regex. So, how to parse the _VIEWSTATE ? I am using HttpURLConnection/HttpsURLConnection in an AsyncTask. Also, don't I need to put the InputStream reader first, to get the _VIEWSTATE first? All the android examples put the input stream after the output stream. Here is what my code looks like so far (posting to one site that has three pages that have to be "clicked through"):
In my Activity, I call the Async task like this:
//execute AsyncTask for all three reports
submit_report.execute(report1, report2, report3);
My Async task doInBackground method:
class UploadReportTask extends AsyncTask<HashMap<String,String>, ProgressBar, Void> {
//this is called on task.execute
protected Void doInBackground(HashMap<String,String>...maps) {
System.out.println("Report is being uploaded");
URL url = null;
try {
url = new URL(getString(R.string.url_dnc));
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept-Charset", utf);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + utf);
urlConnection.setChunkedStreamingMode(0);
//For each map in maps, encode the map,
//get the headers, add the headers to the map, convert to bytes,
//then post the bytes,
//get response.
for (HashMap<String,String> map : maps){
byte[] payload = makePayload(map);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
//urlConn.connect //I think this happens here
out.write(payload);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int length = in.read();
String result, line = reader.readLine();
result = line;
while (length != -1){
result+=line;
}
System.out.println(result);
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
finally{
urlConnection.disconnect();
}
return null;
}
protected String parseViewstate(String response){
int i = 0;
String viewstate = "";
while (true){
int found = response.indexOf("\"__VIEWSTATE\"", i);
if (found == -1) break;
int start = found + 38; //check numbers from start of "__V"
int end = (response.indexOf("/>", start)) -2;
viewstate = response.substring(start, end);
i = end + 1;
}return viewstate;
}

File in java not downloading correctly

I want to download a file from a Server into a client machine. But i want the file to be downloaded from a browser : I want the file to be saved at the Downloads Folder.
Im using the following code to download files.
public void descarga(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
// Get the URL
URL url = new URL(address);
// Open an output stream to the destination file on our local filesystem
out = new BufferedOutputStream(new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
// Get the data
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
// Done! Just clean up and get out
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
// Shouldn't happen, maybe add some logging here if you are not
// fooling around ;)
}
}
It works but unless i specify the absolute path it does not download the file, therefore is useless to use from different clients with different browsers, because the webpage does not even prompts the message that lets the user know that a file is being downloaded. What can i add to get that to work?
Thanks

Categories