如何使用PUT方法将文件发送到Web服务

时间:2016-04-19 09:16:40

标签: java json file-upload http-put

我正在尝试使用PUT方法上传文件。我之前被告知使用POST并进行分段上传,但我的Web服务只允许GET,PUT,PATCH,DELETE,HEAD和OPTIONS。主要原因是我正在更新包含id,target,source,file的JSON数组。现在我只需要更新Web服务中的文件部分,即我必须在那里上传文件。

这是我的代码:

URLConnection urlconnection = null;
    try{
        File file = new File("/Users/pathtofile/file.pdb");
        URL url = new URL("http://example.website/api/jobs/5/");
        urlconnection = url.openConnection();
        urlconnection.setDoOutput(true);
        urlconnection.setDoInput(true);

        if (urlconnection instanceof HttpURLConnection) {
            try {
                ((HttpURLConnection)urlconnection).setRequestMethod("PUT");
                ((HttpURLConnection)urlconnection).setRequestProperty("Content-Type",
                        "application/json");

                ((HttpURLConnection)urlconnection).connect();
            } catch (ProtocolException e) {
                // TODO Auto-generated catch block
                System.out.println("ProtocolException");
                e.printStackTrace();
            }
        }
        BufferedOutputStream bos = new BufferedOutputStream(urlconnection
                .getOutputStream());
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                file));
        int i;
        // read byte by byte until end of stream
        while ((i = bis.read()) >= 0) {
            bos.write(i);
        }
        bos.close();
        // Getting error here (Bad request).
        System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());

    } catch(Exception e) {
        System.out.println("Exception");
        e.printStackTrace();
    }
    try {
        InputStream inputStream;
        int responseCode = ((HttpURLConnection)urlconnection).getResponseCode();
        if ((responseCode >= 200) && (responseCode <= 202)) {
            inputStream = ((HttpURLConnection)urlconnection).getInputStream();
            int j;
            while ((j = inputStream.read()) >= 0) {
                System.out.println(j);
            }
        } else {
            System.out.println(responseCode);
            inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
            System.out.println(inputStream);
        }
        ((HttpURLConnection)urlconnection).disconnect();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("IOException");
        e.printStackTrace();
    }

我收到以下错误:

Bad Request
400

有没有办法使用PUT方法发送文件?该文件将在一个地方lıke:

{"target":["This field is required."],
"project":["This field is required."],
"option":["This field is required."],
"result_file":["No file was submitted."],
"com_status":["This field is required."]}

上面是curl PUT方法的输出,我试过没有给出任何参数。它还表明参数是JSON格式所必需的。

0 个答案:

没有答案