在java中的http post中的参数上发送文件

时间:2019-07-19 22:24:19

标签: java parameters http-post multifile-uploader

我想通过使用HTTP Post将参数传递给文本文件来上传文本文件。在下面的代码中,当前正在将文件上传到URL,而不通过参数传递文件(这是错误的)。但是该URL仅通过文件参数接受文件。我想通过将其传递给参数来上传我的文件,以使其成功在网站上上传。上传后,我想显示响应正文。在使用HTTP Post通过文件参数传递文本文件的过程中,我需要帮助。 对编程非常新。 任何帮助将不胜感激。

public class httpPostExample {
static final String UPLOAD_URL ="http://www.example.com/";
static final int BUFFER_SIZE = 4096;

public static void main(String[] args) throws Exception {

    System.out.println("Current logged User: " + 
System.getProperty("user.name"));
    File uploadFile = new File("location of the file to be uploaded");

    System.out.println("File to upload: " + uploadFile);

    // creates a HTTP connection
    URL url = new URL(UPLOAD_URL);
    HttpURLConnection httpConn = (HttpURLConnection) 
    url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true);
    httpConn.setRequestMethod("POST");
    // sets file name as a HTTP header
    httpConn.setRequestProperty("fileName", uploadFile.getName());

    // opens output stream of the HTTP connection for writing data
    OutputStream outputStream = httpConn.getOutputStream();

    // Opens input stream of the file for reading data
    FileInputStream inputStream = new FileInputStream(uploadFile);
    System.out.println("inputStream : " + inputStream);

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    System.out.println("Start writing data...");

    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }

    System.out.println("Data was written.");
    outputStream.close();
    inputStream.close();

    // check HTTP response from server

    receiveResponse(httpConn);
}

public static String receiveResponse(HttpURLConnection conn)
      throws IOException {
    conn.setConnectTimeout(10000);
    conn.setReadTimeout(10000);
    // retrieve the response from server
    InputStream is = null;
    try {
      is = conn.getInputStream();
      int ch;
      StringBuffer sb = new StringBuffer();
      while ((ch = is.read()) != -1) {
        sb.append((char) ch);
      }
      System.out.println("response body:" + sb);
      return sb.toString();
    } catch (IOException e) {
      throw e;
    } finally {
      if (is != null) {
        is.close();
      }
    }
  }
}

0 个答案:

没有答案