[Erledigt] Datei hochladen über Jakarta Commons HttpClient

Ich probiere gerade, eine Datei mit den Jakarta Commons (HttpClient) auf eine Website hochzuladen.

Das Formular sieht folgendermaßen aus:
[xml]





[/xml]

Mein Lösungsansatz:


import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.methods.multipart.*;

public class UploadTest {

	public static void main(String[] args) {
		new UploadTest.los();
	}

	public void los() {
		File input = new File(getClass().getResource("MeineDatei").getFile());
		PostMethod post = new PostMethod("http://www.example.com/uploaded.php");

		RequestEntity entity = new FileRequestEntity(input,
				"multipart/form-data; charset=ISO-8859-1");
		post.setRequestEntity(entity);
		
		try {
			post.setRequestBody(new FileInputStream(input));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		HttpClient httpclient = new HttpClient();
		try {
			httpclient.executeMethod(post);
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			System.out.println(post.getResponseBodyAsString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		post.releaseConnection();
	}
}

Das Problem ist, ich muss uploaded.php irgendwie mitteilen, dass sich die Datei unter dem Parameter uploadfile befindet. Wie gehe ich vor?
Oder ist mein Lösungsansatz falsch?

Hi,

habe im Moment gerade mit der API zu tun, jedoch nicht in dem Bereich. Hab mich trotzdem mal umgesehn, das hier:

ClientFormLogin.java

sollte für dich interessant sein. Augenmerk liegt auf

        nvps.add(new BasicNameValuePair("IDToken1", "username"));
        nvps.add(new BasicNameValuePair("IDToken2", "password"));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        response = httpclient.execute(httpost);
        entity = response.getEntity();```

Vermute also mal, dass es irgendwie mit der NameValuePair Liste in der Post Entity geht. Wenn du nicht weiter kommst meldest dich nochmal, dann schau ich mal genauer.

Gruß
Rev

Das Problem ist, das ganze läuft über multipart/form-data (s. Formular).

Hab mir jetzt mal eine Lösung zusammengebastelt (über einen einfachen Socket):

import java.net.*;

public class UploadExample {

	public static void main(String args[]) {
		new UploadExample().los();
	}
	
	public void los() {
		try {
			String hostname = "www.xyz.de";
			int port = 80;
			Socket socket = new Socket(hostname, port);

			// Send header
			String path = "/uploaded.php";

			// File To Upload
			File theFile = new File(getClass().getResource("dasBild.jpg")
					.getFile());

			System.out.println("size: " + (int) theFile.length());
			DataInputStream fis = new DataInputStream(new BufferedInputStream(
					new FileInputStream(theFile)));
			byte[] theData = new byte[(int) theFile.length()];

			fis.readFully(theData);
			fis.close();

			DataOutputStream raw = new DataOutputStream(socket
					.getOutputStream());
			Writer wr = new OutputStreamWriter(raw);

			String command = "--dill
"
					+ "Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
					+ theFile.getName() + "\"
"
					+ "Content-Type: image/jpeg
" + "
";

			String trail = "
--dill--
";

			String header = "POST "
					+ path
					+ " HTTP/1.0
"
					+ "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
"
					+ "Accept-Language: de-de,de;q=0.5
"
					+ "Accept-Encoding: gzip,deflate"
					+ "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"
					+ "Keep-Alive: 300"
					+ "Connection: Keep-Alive
"
					+ "Referer: http://" + hostname + "/
"
					+ "Cookie: "
					+ "Content-Type: multipart/form-data; boundary=dill
"
					+ "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
"
					+ "Host: " + hostname + "
"
					+ "Content-Length: "
					+ ((int) theFile.length() + command.length() + trail
							.length()) + "

" 
					+ "Pragma: no-cache
" + "
";

			wr.write(header);
			wr.write(command);

			wr.flush();
			raw.write(theData);
			raw.flush();
			wr.write("
--dill--
");
			wr.flush();

			BufferedReader rd = new BufferedReader(new InputStreamReader(socket
					.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null) {
				System.out.println(line);
			}
			wr.close();
			raw.close();

			socket.close();
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}
}```

Jetzt ist die Frage: Wie überliefere ich der Website noch andere (POST-)Parameter?

Also kommt so eine HTTP-Anfrage raus:

POST /uploaded.php HTTP/1.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de-de,de;q=0.5
Accept-Encoding: gzip,deflateAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300
Connection: Keep-Alive
Referer: http://www.xyz.de/
Cookie: 
Content-Type: multipart/form-data; boundary=dill
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
Host: www.xyz.de
Content-Length: 299798

Pragma: no-cache

--dill
Content-Disposition: form-data; name="uploadfile"; filename="dasBild.jpg"
Content-Type: image/jpeg

/* Die Datei */
--dill--

Nach **ewigem **googeln hab ich ne Lösung gefunden:

import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.MultipartPostMethod;

public class HttpMultiPartFileUpload {
    private static String url =
      "http://www.xyz.de/uploaded.php";

    public static void main(String[] args) throws IOException {
    	new HttpMultiPartFileUpload().los();
    }
    
    public void los() {
    	   HttpClient client = new HttpClient();
           MultipartPostMethod mPost = new MultipartPostMethod(url);
           client.setConnectionTimeout(8000);
           File f1 = new File(getClass()
   				.getResource("MeinBild.jpg").getFile());
   		f1 = new File(String.valueOf(f1).replace("%20", " "));

           System.out.println("File1 Length = " + f1.length());

           try {
			mPost.addParameter("xupload1file", f1);
		} catch (FileNotFoundException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
           mPost.addParameter("gallery", "none");
           mPost.addParameter("resize", "no-resize");

           try {
			int statusCode1 = client.executeMethod(mPost);
		} catch (HttpException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

           System.out.println("statusLine>>>" + mPost.getStatusLine());
           try {
			System.out.println(mPost.getResponseBodyAsString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
           mPost.releaseConnection();
    }
}```