0

我正在尝试将 post 方法中的 URL 中的两个参数传递给 http 连接,但没有获得任何成功,任何人都可以帮我解决代码是

URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // add request header
    con.setRequestMethod("POST");
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

    JsonObject requestData = new JsonObject();
    requestData.addProperty("email", "nitin@eye-watch.in");
    requestData.addProperty("name", "nitin malik");
    requestData.addProperty("phone_no", "9540825737");

    File fileToUpload = new File("/home/nitin/Desktop/clientdcs.jpg");

    String urlParameters = "form=" + requestData.toString() + "&file=" + fileToUpload;

    // Send post request
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
4

1 回答 1

0

当您想要发送文件的内容时,您通常希望使用multipart/form-data作为 Content-Type。

可以使用 JavaMail 库构建 multipart/form-data 消息:

MimeBodyPart formPart = new MimeBodyPart();
formPart.setContent(
    URLEncoder.encode(requestData.toString(), "UTF-8"),
    "application/x-www-form-urlencoded");
formPart.setDisposition("form-data; name=\"form\"");

MimeBodyPart filePart = new MimeBodyPart();
filePart.attachFile(fileToUpload);
ContentDisposition disposition = new ContentDisposition("form-data");
disposition.getParameterList().set("name", "file");
disposition.getParameterList().set("filename", fileToUpload.toString(), "UTF-8");
filePart.setDisposition(disposition.toString());

MimeMultipart multipart = new MimeMultipart("form-data");
multipart.addBodyPart(formPart);
multipart.addBodyPart(filePart);

try (OutputStream out = con.getOutputStream()) {
    multipart.writeTo(out);
}

getPartServlet 可以使用HttpServletRequest的方法读取表单数据:

Part formPart = request.getPart("form");
ByteBuffer buffer = ByteBuffer.allocate((int) formPart.getSize());
try (ReadableByteChannel in =
        Channels.newChannel(formPart.getInputStream()) {
    while (buffer.hasRemaining()) {
        in.read(buffer);
    }
}
String encoded = new String(buffer.array(), StandardCharsets.UTF_8);
String form = URLDecoder.decode(encoded, "UTF-8");

Part filePart = request.getPart("file");
File sentFile = new File(filePart.getName());
File file = new File(downloadDirectory, sentFile.getName());
filePart.write(file.toString());
于 2013-11-10T16:30:37.630 回答