来自java的multipart文件上传发布请求

我正在尝试制作一个程序,将图像上传到接受多部分文件上传的网络服务器。

更具体地说,我想向http://iqs.me发出http POST请求,该请求在变量“pic”中发送文件。

我做了很多尝试,但我不知道我是否已经接近了。 最难的部分似乎是获取HttpURLConnection来发出POST类型的请求。 我得到的响应看起来像是一个GET。

(我想在没有任何第三方库的情况下这样做)

更新:非工作代码在这里(没有错误,但似乎没有POST):

HttpURLConnection conn = null; BufferedReader br = null; DataOutputStream dos = null; DataInputStream inStream = null; InputStream is = null; OutputStream os = null; boolean ret = false; String StrMessage = ""; String exsistingFileName = "myScreenShot.png"; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1*1024*1024; String responseFromServer = ""; String urlString = "http://iqs.local.com/index.php"; try{ FileInputStream fileInputStream = new FileInputStream( new File(exsistingFileName) ); URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); dos = new DataOutputStream( conn.getOutputStream() ); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"pic\";" + " filename=\"" + exsistingFileName +"\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0){ dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); fileInputStream.close(); dos.flush(); dos.close(); }catch (MalformedURLException ex){ System.out.println("Error:"+ex); }catch (IOException ioe){ System.out.println("Error:"+ioe); } try{ inStream = new DataInputStream ( conn.getInputStream() ); String str; while (( str = inStream.readLine()) != null){ System.out.println(str); } inStream.close(); }catch (IOException ioex){ System.out.println("Error: "+ioex); } 

两件事情:

  1. 确保调用setRequestMethod将HTTP请求设置为POST 。 应该警告您手动执行多部分POST请求很困难且容易出错。

  2. 如果你在* NIX上运行,那么netcat工具对于调试这些东西非常有用。 跑
    netcat -l -p 3000

    并将您的程序指向端口3000; 你会看到程序发送的确切内容(Control-C后来关闭它)。

我已经使用过它,发现它在多部分文件上传中很有用

 File f = new File(filePath); PostMethod filePost = new PostMethod(url); Part[] parts = { new FilePart("file", f) }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); status = client.executeMethod(filePost);