来自java的多部分文件上传post请求

发布于 2024-08-29 04:41:07 字数 2649 浏览 1 评论 0原文

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

更具体地说,我想向 http://iqs.me 发出一个 http POST 请求,发送变量中的文件“图片”。

我已经做了很多尝试,但我不知道我是否已经接近了。最困难的部分似乎是获取 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);
  }

I'm trying to make a program that uploads a image to a webserver that accepts multipart file-uploads.

More specificly i want to make a http POST request to http://iqs.me that sends a file in the variable "pic".

I've made a lot of tries but i don't know if i've even been close. The hardest part seems to be to get a HttpURLConnection to make a request of the type POST. The response i get looks like it makes a GET.

(And i want to do this without any third party libs)

UPDATE: non-working code goes here (no errors but doesn't seem to do a 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);
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

坏尐絯 2024-09-05 04:41:07

两件事:

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

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

    并将你的程序指向端口 3000;您将准确地看到程序正在发送的内容(随后按 Control-C 关闭它)。

Two things:

  1. Make sure you call setRequestMethod to set the HTTP request to be a POST. You should be warned that doing multipart POST requests by hand is difficult and error-prone.

  2. If you're running on *NIX, the tool netcat is very useful for debugging this stuff. Run
    netcat -l -p 3000

    and point your program to port 3000; you'll see exactly what the program is sending (Control-C to close it afterwards).

薄荷梦 2024-09-05 04:41:07

我已经使用过它并发现它在分段文件上传中很有用

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);

I have used this and found it useful in multipart file upload

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文