Java Http 客户端通过 POST 上传文件

问题描述 投票:0回答:6

我正在开发一个 J2ME 客户端,它必须使用 HTTP 将文件上传到 Servlet。

使用 Apache Commons FileUpload 涵盖 servlet 部分

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
{       

    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(1000000);

    File fileItems = upload.parseRequest(request);

    // Process the uploaded items
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        File file = new File("\files\\"+item.getName());
        item.write(file);
    }
}

Commons Upload 似乎只能上传多部分文件,但不能上传 application/octect-stream。

但是对于客户端来说,没有 Multipart 类,在这种情况下,也不能使用任何 HttpClient 库。

其他选项可能是使用 HTTP 块上传,但我还没有找到如何实现的明确示例,特别是在 servlet 方面。

我的选择是: - 实现一个用于http块上传的servlet - 实现用于 http 多部分创建的原始客户端

我不知道如何实现上述选项。 有什么建议吗?

java http servlets file-upload java-me
6个回答
32
投票

通过 HTTP 发送文件应该使用

multipart/form-data
编码。您的 servlet 部分很好,因为它已经使用 Apache Commons FileUpload 来解析
multipart/form-data
请求。虽然自从 Servlet 3.0 引入了
request.getPart()
方法以来就没有必要了。另请参阅如何使用 JSP/Servlet 将文件上传到服务器?

但是,您的客户端部分不正确,因为您似乎将原始文件内容写入请求正文。您需要确保您的客户发送正确的

multipart/form-data
请求。具体如何执行取决于您用于发送 HTTP 请求的 API。如果它是普通的
java.net.URLConnection
,那么你可以在这个答案底部附近找到一个具体的例子。如果您为此使用 Apache HttpComponents Client,那么这里有一个基于 他们的文档的具体示例:

String url = "https://example.com";
File file = new File("/example.ext");

try (CloseableHttpClient client = HttpClients.createDefault()) {
    HttpPost post = new HttpPost(url);
    HttpEntity entity = MultipartEntityBuilder.create().addPart("file", new FileBody(file)).build();
    post.setEntity(entity);

    try (CloseableHttpResponse response = client.execute(post)) {
        // ...
    }
}

与具体问题无关,您的服务器端代码中有一个错误:

File file = new File("\files\\"+item.getName());
item.write(file);

这可能会覆盖任何以前上传的同名文件。我建议使用

File#createTempFile()
来代替。

String name = FilenameUtils.getBaseName(item.getName());
String ext = FilenameUtils.getExtension(item.getName());
File file = File.createTempFile(name + "_", "." + ext, new File("/files"));
item.write(file);

13
投票

以下代码可用于使用 HTTP Client 4.x 上传文件(以上答案使用 MultipartEntity,现已弃用)

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

String uploadFile(String url, File file) throws IOException
{
    HttpPost post = new HttpPost(url);
    post.setHeader("Accept", "application/json");
    _addAuthHeader(post);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    // fileParamName should be replaced with parameter name your REST API expect.
    builder.addPart("fileParamName", new FileBody(file));
    //builder.addPart("optionalParam", new StringBody("true", ContentType.create("text/plain", Consts.ASCII)));
    post.setEntity(builder.build());
    HttpResponse response = getClient().execute(post);;
    int httpStatus = response.getStatusLine().getStatusCode();
    String responseMsg = EntityUtils.toString(response.getEntity(), "UTF-8");

    // If the returned HTTP response code is not in 200 series then
    // throw the error
    if (httpStatus < 200 || httpStatus > 300) {
        throw new IOException("HTTP " + httpStatus + " - Error during upload of file: " + responseMsg);
    }

    return responseMsg;
}

您将需要以下 Apache 库的最新版本:httpclient、httpcore、httpmime。

getClient()
可以替换为
HttpClients.createDefault()


3
投票

请查找在 Java 中使用 HttpClient 的文件上传功能的示例工作示例。

package test;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class fileUpload {
private static void executeRequest(HttpPost httpPost) {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(httpPost);
        System.out.println("Response Code:  " + response.getStatusLine().getStatusCode());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void executeMultiPartRequest(String urlString, File file) throws IOException {
    HttpPost postRequest = new HttpPost(urlString);
    postRequest = addHeader(postRequest, "Access Token");
    try {
        postRequest.setEntity(new FileEntity(file));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    executeRequest(postRequest);
}

private static HttpPost addHeader(HttpPost httpPost, String accessToken) {
    httpPost.addHeader("Accept", "application/json;odata=verbose");
    httpPost.setHeader("Authorization", "Bearer " + accessToken);
    return httpPost;
}

public static void main(String args[]) throws IOException {
    fileUpload fileUpload = new fileUpload();
    File file = new File("C:\\users\\bgulati\\Desktop\\test.docx");
    fileUpload.executeMultiPartRequest(
            "Here Goes the URL", file);

}
}

0
投票

古老的问题和最佳答案依赖于错误的陈述。

通过 HTTP 发送文件应该使用多部分/表单数据编码。

以 OCTET-STREAM 形式发送文件效率更高。

JDK11+客户端代码:

HttpRequest request = HttpRequest.newBuilder()
    .uri(new URI("http://YOUR-SERVER:PORT/ENDPOINT"))
    .timeout(Duration.of(60, SECONDS))
    .POST(HttpRequest.BodyPublishers.ofInputStream(is))
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

-1
投票

感谢我截取的所有代码...这是一些回来的代码。

Gradle

compile "org.apache.httpcomponents:httpclient:4.4"  
compile "org.apache.httpcomponents:httpmime:4.4"



import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;


public class HttpClientUtils {

    public static String post(String postUrl, Map<String, String> params,
            Map<String, String> files) throws ClientProtocolException,
            IOException {
        CloseableHttpResponse response = null;
        InputStream is = null;
        String results = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();

        try {

            HttpPost httppost = new HttpPost(postUrl);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();

            if (params != null) {
                for (String key : params.keySet()) {
                    StringBody value = new StringBody(params.get(key),
                            ContentType.TEXT_PLAIN);
                    builder.addPart(key, value);
                }
            }

            if (files != null && files.size() > 0) {
                for (String key : files.keySet()) {
                    String value = files.get(key);
                    FileBody body = new FileBody(new File(value));
                    builder.addPart(key, body);
                }
            }

            HttpEntity reqEntity = builder.build();
            httppost.setEntity(reqEntity);

            response = httpclient.execute(httppost);
            // assertEquals(200, response.getStatusLine().getStatusCode());

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                is = entity.getContent();
                StringWriter writer = new StringWriter();
                IOUtils.copy(is, writer, "UTF-8");
                results = writer.toString();
            }

        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Throwable t) {
                // No-op
            }

            try {
                if (response != null) {
                    response.close();
                }
            } catch (Throwable t) {
                // No-op
            }

            httpclient.close();
        }

        return results;
    }

    public static String get(String getStr) throws IOException,
            ClientProtocolException {
        CloseableHttpResponse response = null;
        InputStream is = null;
        String results = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();

        try {
            HttpGet httpGet = new HttpGet(getStr);
            response = httpclient.execute(httpGet);

            assertEquals(200, response.getStatusLine().getStatusCode());

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                is = entity.getContent();
                StringWriter writer = new StringWriter();
                IOUtils.copy(is, writer, "UTF-8");
                results = writer.toString();
            }

        } finally {

            try {
                if (is != null) {
                    is.close();
                }
            } catch (Throwable t) {
                // No-op
            }

            try {
                if (response != null) {
                    response.close();
                }
            } catch (Throwable t) {
                // No-op
            }

            httpclient.close();
        }

        return results;
    }

}

-2
投票

无需输入血腥细节,您的代码看起来就很好。

现在您需要服务器端。我建议您使用 Jakarta FileUpload,这样您就不必执行任何操作。只需部署和配置即可。

© www.soinside.com 2019 - 2024. All rights reserved.