我有一个传入的HttpServletRequest,它包含一个我需要传递给新的httpUrlConnection的请求部分

时间:2015-12-30 17:13:23

标签: java api rest

让我看看能否解释一下。前端为我提供了一个电子表格,我需要通过api调用将其传递到我的中央服务器来进行处理。我使用以下代码来提取电子表格并创建我的工作簿,

Part spreadsheet = request.getPart(SPREADSHEET);
Workbook workbook = WorkbookFactory.create(spreadsheet.getInputStream());

其中'request'是传入的HttpServletRequest对象。我知道它可以工作,我可以操作电子表格,但我需要将它传递给我的其他服务器进行处理,我无法弄清楚如何做到这一点。这是我到目前为止所拥有的。

@Path("/uploadSpreadsheet")
@POST
public String uploadSpreadsheet(@Context final HttpServletRequest request,@Context final HttpHeaders httpHeaders) throws IOException, ServletException, InvalidFormatException, JSONException {
    return uploadUtil(request, "rest/memberService/uploadSpreadsheet");
}

这是我无法做到的工具。

private String uploadUtil(HttpServletRequest request, String serviceUrl) throws MalformedURLException, ProtocolException, IOException, ServletException {
    String baseUrl = "http://localhost:8084/centralservices/";
    String urlString = baseUrl.concat(serviceUrl);
    URL url = new URL(urlString);
    String boundary = "===" + System.currentTimeMillis() + "===";       
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

    httpCon.setDoOutput(true);
    httpCon.setRequestMethod("POST");
    httpCon.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpCon.setRequestProperty("Key", "SOMEKEYHERE");
    httpCon.setRequestProperty("clientAddress", request.getRemoteAddr());

    //I know this is wrong but I'm not sure what goes here:
    httpCon.setRequestProperty("file", request.getPart(SPREADSHEET));

    int responseCode;

    StringBuilder resp = new StringBuilder();
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            resp.append(inputLine);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        httpCon.disconnect();
    }

    return resp.toString();
}

希望这是有道理的。我的意思是我真正需要做的就是将请求相同(将所有formpart和所有内容)转移到不同的URL。一旦它到达那里我没有处理它的问题。如果我对某些事情不清楚,请告诉我。我对这些东西很新。我们已经有一个休息实用程序,我一直用于其他所有东西,但它不适用于这种情况,所以我需要创建一个新的。

3 个答案:

答案 0 :(得分:0)

如果您使用的是Servlet-Api 3.0,则以下方法将为您提供如何读取流并将流写回后续URL的信息。

http://balusc.omnifaces.org/2009/12/uploading-files-in-servlet-30.html

从上面的代码中,获得Part后,将获取的文件/工作簿转换为bytebuffer,然后将其写入Output stream。

connection.getOutputStream()写(filebuff);

因为在这种情况下添加到请求属性将无济于事。

由于 Maruthi

答案 1 :(得分:0)

我认为多部分请求中缺少很多东西。看到这个链接 Sending files using POST with HttpURLConnection

使用某些API为您完成此操作可能更好,最简单的可能是apache httpclient

请参阅this SO post

中的示例用法

如果您确实需要使用URLConnection,那么您可以使用此multipart utility from codejava.net

我在这里发布代码以备份,以防原始链接出现故障。

<强> MultipartUtility

package net.codejava.networking;

import java.io.BufferedReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * This utility class provides an abstraction layer for sending multipart HTTP
 * POST requests to a web server.
 * @author www.codejava.net
 *
 */
public class MultipartUtility {
    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     * @param requestURL
     * @param charset
     * @throws IOException
     */
    public MultipartUtility(String requestURL, String charset)
            throws IOException {
        this.charset = charset;

        // creates a unique boundary based on time stamp
        boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
        /*Following line has no significance for the task this utility performs*/
        /*httpConn.setRequestProperty("Test", "Bonjour");*/
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                true);
    }

    /**
     * Adds a form field to the request
     * @param name field name
     * @param value field value
     */
    public void addFormField(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
                .append(LINE_FEED);
        writer.append("Content-Type: text/plain; charset=" + charset).append(
                LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a upload file section to the request
     * @param fieldName name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName
                        + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(fileName))
                .append(LINE_FEED);
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        inputStream.close();

        writer.append(LINE_FEED);
        writer.flush();    
    }

    /**
     * Adds a header field to the request.
     * @param name - name of the header field
     * @param value - value of the header field
     */
    public void addHeaderField(String name, String value) {
        writer.append(name + ": " + value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Completes the request and receives response from the server.
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public List<String> finish() throws IOException {
        List<String> response = new ArrayList<String>();

        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                response.add(line);
            }
            reader.close();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response;
    }
}

测试计划

package net.codejava.networking;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * This program demonstrates a usage of the MultipartUtility class.
 * @author www.codejava.net
 *
 */
public class MultipartFileUploader {

    public static void main(String[] args) {
        String charset = "UTF-8";
        File uploadFile1 = new File("e:/Test/PIC1.JPG");
        File uploadFile2 = new File("e:/Test/PIC2.JPG");
        String requestURL = "http://localhost:8080/FileUploadSpringMVC/uploadFile.do";

        try {
            MultipartUtility multipart = new MultipartUtility(requestURL, charset);

            multipart.addHeaderField("User-Agent", "CodeJava");
            multipart.addHeaderField("Test-Header", "Header-Value");

            multipart.addFormField("description", "Cool Pictures");
            multipart.addFormField("keywords", "Java,upload,Spring");

            multipart.addFilePart("fileUpload", uploadFile1);
            multipart.addFilePart("fileUpload", uploadFile2);

            List<String> response = multipart.finish();

            System.out.println("SERVER REPLIED:");

            for (String line : response) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
}

答案 2 :(得分:0)

我对所提出的一些选项太不熟悉所以我只是将电子表格转换为json字符串并将其与现有的rest实用程序一起发送。