HTTP POST in JAVA

geschrieben für helma (siehe http://helma.org ), nicht getestet für PHP

folgende funktion sendet ein file als ByteStream zu einer URL:


import java.net.URL;
import java.io.File;
import java.io.InputStream;
import java.net.URLConnection;
import java.io.FileInputStream;
import java.io.OutputStream;

// class definition

/**
* send file via HTTP POST to uri
*/
public static void sendfile() {
// some text that does not appear in the file
// use an evan number of “-”
String CONTENT_BOUNDARY = “–abc”;
FileInputStream fis1 = null;
OutputStream os1 = null;
InputStream is1 = null;
try {
// the URL of your upload application
URL testPost = new URL(“http://myurl/myaction?userid=a&password=a”);
URLConnection conn = testPost.openConnection();
// conn.setAllowUserInteraction(true);
conn.setDoOutput(true); // turns it into a post
conn.setRequestProperty(“Content-Type”,
“multipart/form-data; boundary=” + CONTENT_BOUNDARY);
// conn.setRequestProperty(“User-Agent”, “Mozilla/4.7 [en] (WinNT; U)”);
// conn.setRequestProperty(“Accept-Language”, “en-us”);
// conn.setRequestProperty(“Accept-Encoding”, “gzip, deflate”);
// conn.setRequestProperty(“Accept”, “image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/vnd.ms-powerpoint, application/pdf, application/x-comet, */*”);
// conn.setRequestProperty(“CACHE-CONTROL”, “no-cache”);
os1 = conn.getOutputStream();
// the file, name is “rawfile”
// whatever file you care to upload
String uploadFileName = “C:\\myfile”;

File file1 = new File(uploadFileName);
fis1 = new FileInputStream(file1);

os1.write( (“-” + CONTENT_BOUNDARY + “\r\n” +
“Content-Disposition: form-data; name=\”rawfile\”; filename=\”” +
uploadFileName
+ “\”\r\nContent-Type: text/plain\r\n\r\n”).getBytes());

byte[] fileStuff = new byte[512];
int howMany = -1;
int totMany = 0;
howMany = fis1.read(fileStuff, 0, 512);
while (howMany != -1) {
totMany += howMany;
os1.write(fileStuff, 0, howMany);
howMany = fis1.read(fileStuff, 0, 512);
}
System.err.println(“read ” + totMany +
” bytes from file, wrote to outputstream.”);
fis1.close();
fis1 = null;
os1.write( (“\r\n–” + CONTENT_BOUNDARY + “–\r\n”).getBytes());

is1 = conn.getInputStream();
byte[] urlStuff = new byte[512];
howMany = is1.read(urlStuff, 0, 512);
while (howMany != -1) {
System.out.write(urlStuff, 0, howMany);
howMany = is1.read(urlStuff, 0, 512);
}
System.err.println(“that was your output.”);
is1.close();
is1 = null;
os1.close();
os1 = null;
}
catch (Exception ex) {
System.err.println(“Exception: ” + ex);
ex.printStackTrace();
}
finally {
if (fis1 != null)
try {
fis1.close();
}
catch (Exception ok_to_eat) {
// ok to ignore this
}
if (is1 != null)
try {
is1.close();
}
catch (Exception ok_to_eat) {
// ok to ignore this
}
if (os1 != null)
try {
os1.close();
}
catch (Exception ok_to_eat) {
// ok to ignore this
}
}
}

Advertisement