如何在URL中传递多个参数

时间:2013-11-09 11:33:56

标签: java http java-ee servlets

我正在尝试将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();

1 个答案:

答案 0 :(得分:0)

如果要发送文件内容,通常需要使用multipart/form-data作为内容类型。

可以使用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);
}

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

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