上传文件示例代码

package com.imooc.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
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.StringEntity;
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;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * java 文件上传示例
 * 适用于验证码识别接口 https://www.juhe.cn/docs/api/id/60
 * 违章代缴上传证件接口 https://www.juhe.cn/docs/api/id/238/aid/937
 * 证件识别接口 https://www.juhe.cn/docs/api/id/153/aid/493
 * 示例采用maven管理jar包,所用jar包如下,下载时请注意版本:
 * <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
 * <dependency>
 * <groupId>org.apache.httpcomponents</groupId>
 * <artifactId>httpclient</artifactId>
 * <version>4.5.6</version>
 * </dependency>
 * <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
 * <dependency>
 * <groupId>org.apache.httpcomponents</groupId>
 * <artifactId>httpmime</artifactId>
 * <version>4.5.6</version>
 * </dependency>
 */
public class HttpUtil {

    //发送无参数名数据设置的请求头Content-Type
    public static final String APPLICATION_JSON = "application/json";
    //字符编码
    public static final String CHARSET_UTF8 = "UTF-8";

    // 从连接池中获取连接的超时时间  
    public static int connectionRequestTimeout = -1;

    //与服务器连接超时时间:httpclient会创建一个异步线程用以创建socket连接,此处设置该socket的连接超时时间  
    public static int connectTimeout = -1;

    //socket读数据超时时间:从服务器获取响应数据的超时时间  
    public static int socketTimeout = -1;

    public static void main(String args[]) {
        // 发送get请求
        System.out.println(get("http://wwww.baidu.com"));

        // post发送json数据
        HttpUtil httpUtil = new HttpUtil();
        System.out.println(httpUtil.postJson("http://silk.juhe.com/book/test.php", "{\"a\":\"A\"}"));

        // post无参数名数据
        System.out.println(httpUtil.postData("http://silk.juhe.com/book/test.php", "hello world", null, null));


        // 上传(可以多张图片)图片的同时post一些其他数据
        Map<String, Object> map = new HashMap<>();
        map.put("name", "silk");
        map.put("hobby", "basketball");
        map.put("age", 18);
        map.put("A", new File("D://1M.png"));//图片,参数名为A
        map.put("B", new File("D://1N.png"));//图片,参数名为B
        map.put("C", new File("D://1O.png"));//图片,参数名为C
        System.out.println(HttpUtil.post("http://vv.juhe.cn/book/test.php", map));
    }

    /**
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, Map<String, Object> params) {
        return postData(url, params, null, null);
    }

    /**
     * @param url
     * @param params
     * @param charset
     * @param headers
     * @return
     */
    public static String postData(String url, Map<String, Object> params, String charset, Map<String, String> headers) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        //设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(HttpUtil.connectionRequestTimeout)
                .setConnectTimeout(HttpUtil.connectTimeout)
                .setSocketTimeout(HttpUtil.socketTimeout)
                .build();
        httpPost.setConfig(requestConfig);
        //设置请求头
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpPost.setHeader(header.getKey(), header.getValue());
            }
        }
        //封装提交参数
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        CloseableHttpResponse closeableHttpResponse = null;
        try {
            if (params != null) {
                for (Map.Entry param : params.entrySet()) {
                    if (param.getValue().getClass().equals(File.class)) {
                        multipartEntityBuilder.addPart((String) param.getKey(), new FileBody((File) param.getValue()));
                    } else {
                        System.out.println(param.getValue());
                        multipartEntityBuilder.addPart((String) param.getKey(), new StringBody(param.getValue().toString(), ContentType.TEXT_PLAIN));
                    }
                }
            }
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpPost.setEntity(httpEntity);
            closeableHttpResponse = closeableHttpClient.execute(httpPost);
            //读取响应
            if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = closeableHttpResponse.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpResponse != null) {
                try {
                    closeableHttpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * @param url
     * @return
     */
    public static String get(String url) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse closeableHttpResponse = null;
        try {
            closeableHttpResponse = closeableHttpClient.execute(httpGet);
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            String content = null;
            if (httpEntity != null) {
                content = EntityUtils.toString(httpEntity);
            }
            httpGet.abort();
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpResponse != null) {
                try {
                    closeableHttpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * @param url
     * @param jsonString
     * @return
     */
    public String postJson(String url, String jsonString) {
        return postData(url, jsonString, HttpUtil.APPLICATION_JSON, HttpUtil.CHARSET_UTF8);
    }

    /**
     * @param url
     * @param data
     * @param contentType
     * @param contentEncoding
     * @return
     */
    public String postData(String url, String data, String contentType, String contentEncoding) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        try {
            StringEntity stringEntity = new StringEntity(data);
            stringEntity.setContentEncoding(contentEncoding);
            stringEntity.setContentType(contentType);
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);
            if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity httpEntity = closeableHttpResponse.getEntity();
                if (httpEntity != null) {
                    return EntityUtils.toString(httpEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}


登录 后可发表评论

    最新发布
    聚合数据©版权所有