I want to make a program in swing which connect to tomcat server running locally. with username,password authentication, then user able to upload file in server directory. ie.http://localhost:8080/uploadfiles. from user defined file path , and same as download to the local directory.
Asked
Active
Viewed 1.1k times
0
-
1Have you tried the HttpClient tutorial - http://hc.apache.org/httpcomponents-client-ga/tutorial/html? – Paul Grime Sep 30 '11 at 10:21
-
1The above code got java.net.* package more or less correct. The only thing I've noticed urlconnection.setDoOutput(), which is used for POST requests. Also you should always check urlconnection.getResponseCode() before reading server response. – Eugene Kuleshov Sep 30 '11 at 14:18
-
You need more detail as to what problems you are encountering, how you're handling it on the server end, etc. Lots of unknowns here. – Will Hartung Oct 03 '11 at 05:57
1 Answers
1
Here is one possibility: Download:
URL url = new URL("http://localhost:8080/uploadfiles");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
try {
con.addRequestProperty("Authorization",
"Basic " + encode64(username + ":" + password));
InputStream in = con.getInputStream();
try {
OutputStream out = new FileOutputStream(outFile);
try {
byte buf[] = new byte[4096];
for (int n = in.read(buf); n > 0; n = in.read(buf)) {
out.write(buf, 0, n);
}
} finally {
out.close();
}
} finally {
in.close();
}
} finally {
con.disconnect();
}
Upload:
URL url = new URL("http://localhost:8080/uploadfiles");
HttpURLConnection con = (HttpURLConnection)uploadUrl.openConnection();
try {
con.setDoOutput(true);
con.setRequestMethod("POST");
con.addRequestProperty("Authorization",
"Basic " + encode64(username + ":" + password));
OutputStream out = con.getOutputStream();
try {
InputStream in = new FileInputStream(inFile);
try {
byte buffer[] = new byte[4096];
for (int n = in.read(buffer); n > 0; n = in.read(buffer)) {
out.write(buffer, 0, n);
}
} finally {
in.close();
}
} finally {
out.close();
}
int code = con.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
String msg = con.getResponseMessage();
throw new IOException("HTTP Error " + code + ": " + msg);
}
} finally {
con.disconnect();
}
Now, on the server side, you will need to distinguish between GET and POST requests and handle them accordingly. You will need a library to handle uploads, such as apache FileUpload
Oh, and on the client side, you will need a library that does Base64 encoding such as apache commons codec

Maurice Perry
- 32,610
- 9
- 70
- 97