我错过了发送http部分帖子请求的内容 [英] What did I miss to send a http part post request

查看:133
本文介绍了我错过了发送http部分帖子请求的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用http多部分请求发送图像(稍后我将添加另一个图像)

I am trying to send an image using http multipart request (later I will add another image)

我这样做了:

HttpClient client = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost(
            "http://localhost:8080/ServletExample1/multipart1");
    httpPost.addHeader("Content-Type",
            "multipart/related; boundary=HereItGoes");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    FileBody bin = new FileBody(new File("./test.txt"));
    builder.addPart("bin", bin);
    HttpEntity entity = builder.build();
    httpPost.setEntity(entity);
    HttpResponse response = client.execute(httpPost);
    String responseString = new BasicResponseHandler()
            .handleResponse(response);
    System.out.println(responseString);

在服务器上,我打印部件数量,使用这个:

on the server, I print the number of parts, using this:

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
  if (ServletFileUpload.isMultipartContent(request)) {
    Iterator<Part> partsIterator = request.getParts().iterator();
    System.out.println("The number of parts is :" + request.getParts().size());

,答案总是零,我做了什么错误?

and the answer is always zero, what mistake did i do ?

作为@Jon Skeet,我在添加文件之前创建了请求。现在我重新排序了代码,我把执行作为最后一行,我仍然得到同样的东西,在服务器上的零件数量仍为零

as @Jon Skeet, I was creating the request before adding the file. Now I reordered the code in which I put the execute as the last line, and I still get the same thing, on the server the number of parts, is still zero

推荐答案

看看你何时打电话给执行 - 那是在你建立之前请求正确!只需重新排序您的代码,以便您完全构建请求,然后您发布它以获得响应,然后您使用响应。 (如果在文件构造函数中使用URL,我个人也会感到惊讶,但也许那里有一些时髦的东西...通常文件指的是本地文件系统文件......)

Look at when you're calling execute - that's before you build the request properly! Just reorder your code so that you fully build the request, then you post it to get a response, then you use the response. (I'd also be personally surprised if using a URL in a File constructor worked, but maybe there's something funky going on there... normally File refers to a local filesystem file...)

这篇关于我错过了发送http部分帖子请求的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆