java httpclient post 文件到server
public void sendFileToServer (String url, File logFiles) {
HttpURLConnection connection = null;
OutputStream os = null;
DataInputStream is = null;
try {
// StringBuilder fullUrl = new StringBuilder(url);
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.addRequestProperty("uid", "1935");
connection.addRequestProperty("strlen","11791");
connection.addRequestProperty("bid","16");
connection.addRequestProperty("count", "1");
connection.addRequestProperty("num", "1");
connection.addRequestProperty("type", "3");
// if (customizedHeader != null)
// for (String key : customizedHeader.keySet()) {
// connection.addRequestProperty(key, customizedHeader.get(key));
// }
connection.connect();
FileInputStream iso = new FileInputStream (logFiles);
os = new BufferedOutputStream(connection.getOutputStream());
byte[] buffer = new byte[4096];
int bytes_read;
while ((bytes_read = iso.read(buffer)) != -1) {
os.write(buffer, 0, bytes_read);
}
os.close();
iso.close();
System.out.println("Done... ");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("Upload file success" + connection.getResponseCode());
System.out.println(connection.getContent());
System.out.println(connection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}finally {
try {
if(os != null) {
os.close();
}
} catch (IOException e) {
System.out.println(e.toString());
}
try {
if(is != null) {
is.close();
}
} catch (IOException e) {
System.out.println(e.toString());
}
if(connection != null) {
connection.disconnect();
}
}
}