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

Java Http客户端通过POST上传文件,java,http,servlets,file-upload,java-me,Java,Http,Servlets,File Upload,Java Me,我正在开发一个J2ME客户端,它必须使用HTTP将文件上传到Servlet servlet部分使用ApacheCommonsFileUpload进行介绍 protected void doPost(HttpServletRequest request, HttpServletResponse response) { ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(1000

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

servlet部分使用ApacheCommonsFileUpload进行介绍

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似乎只能上载多部分文件,但不能上载应用程序/octect流

但是对于客户端,没有多部分类,在本例中,也不可能使用任何HttpClient库

另一种选择是使用HTTP块上传,但我还没有找到一个明确的例子来说明如何实现这一点,特别是在servlet端

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

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

如果不输入血淋淋的详细信息,您的代码看起来很好


现在您需要服务器端。我建议您使用雅加达,这样您就不必实现任何东西。只需部署和配置

通过HTTP发送文件应该使用
multipart/form data
编码。您的servlet部分很好,因为它已经用来解析
多部分/表单数据
请求

然而,您的客户机部分显然不是很好,因为您似乎正在将文件内容原始写入请求主体。您需要确保客户端发送正确的
多部分/表单数据请求。具体如何做取决于您用来发送HTTP请求的API。如果它是普通的
java.net.URLConnection
,那么您可以在本文档底部找到一个具体的示例。如果您正在使用,那么下面是一个具体的示例,取自:


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

File file = new File("\files\\"+item.getName());
item.write(file);
这可能会覆盖以前上载的同名文件。我建议用这个来代替

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

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

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;
    }

}
Gradle
编译“org.apache.httpcomponents:httpclient:4.4”
编译“org.apache.httpcomponents:httpmime:4.4”
导入java.io.File;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.StringWriter;
导入java.util.Map;
导入org.apache.commons.io.IOUtils;
导入org.apache.http.HttpEntity;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.methods.CloseableHttpResponse;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.entity.ContentType;
导入org.apache.http.entity.mime.MultipartEntityBuilder;
导入org.apache.http.entity.mime.content.FileBody;
导入org.apache.http.entity.mime.content.StringBody;
导入org.apache.http.impl.client.CloseableHttpClient;
导入org.apache.http.impl.client.HttpClients;
公共类HttpClientUtils{
公共静态字符串post(字符串姿势、映射参数、,
映射文件)引发ClientProtocolException,
IOException{
CloseableHttpResponse响应=null;
InputStream=null;
字符串结果=null;
CloseableHttpClient httpclient=HttpClients.createDefault();
试一试{
HttpPost HttpPost=新的HttpPost(姿态);
MultipartEntityBuilder=MultipartEntityBuilder.create();
如果(参数!=null){
for(字符串键:params.keySet()){
StringBody值=新的StringBody(参数get(键),
ContentType.TEXT(纯文本);
builder.addPart(键、值);
}
}
if(files!=null&&files.size()>0){
for(字符串键:files.keySet()){
字符串值=files.get(key);
FileBody body=newfilebody(新文件(值));
建造商。添加零件(键、主体);
}
}
HttpEntity reqEntity=builder.build();
httppost.setEntity(reqEntity);
response=httpclient.execute(httppost);
//assertEquals(200,response.getStatusLine().getStatusCode());
HttpEntity=response.getEntity();
如果(实体!=null){
is=entity.getContent();
StringWriter编写器=新的StringWriter();
IOUtils.副本(is,作者,“UTF-8”);
结果=writer.toString();
}
}最后{
试一试{
如果(is!=null){
is.close();
}
}捕获(可丢弃的t){
//无操作
}
试一试{
if(响应!=null){
response.close();
}
}捕获(可丢弃的t){
//无操作
}
httpclient.close();
}
返回结果;
}
公共静态字符串get(字符串getStr)引发IOException,
客户端协议异常{
CloseableHttpResponse响应=null;
InputStream=null;
字符串结果=null;
CloseableHttpClient httpclient=HttpClients.createDefault();
试一试{
HttpGet HttpGet=新的HttpGet(getStr);
response=httpclient.execute(httpGet);
assertEquals(200,response.getStatusLine().getStatusCode());
HttpEntity=response.getEntity();
如果(实体!=null){
is=entity.getContent();
StringWriter编写器=新的StringWriter();
IOUtils.副本(is,作者,“UTF-8”);
结果=writer.toString();
}
}最后{
试一试{
如果(is!=null){
is.close();
}
}捕获(可丢弃的t){
//无操作
}
试一试{
if(响应!=null){
response.close();
}
}抓住
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;
    }

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

}
}