JAVA调用http上传文件(可多文件,可传参数)

package com.example.gadgets.util;

import org.apache.commons.httpclient.HttpException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.net.URI;
import java.net.URISyntaxException;
import java.io.*;
import java.net.*;
import java.util.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import java.net.URL;
import java.util.Map;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.util.Date;
import java.util.Map.Entry;

public class HttpClientUtil {
//    public static void get0(String url, String param) {
//        String path = url + "?" + param;
//        CloseableHttpClient client = HttpClients.createDefault();
//        HttpGet get = new HttpGet(path);
//        CloseableHttpResponse resp = null;
//        try {
//            resp = client.execute(get);
//            int code = resp.getStatusLine().getStatusCode();//响应码
//            System.out.println("resp code:" + code);
//            HttpEntity entity = resp.getEntity();
//            String msg = EntityUtils.toString(entity, "UTF-8");//响应信息
//            System.out.println("receive msg:" + msg.substring(0, 200));
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (resp != null) {
//                try {
//                    resp.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }
//
//    public static void get1(String u, String param) throws IOException {
//        // 目标地址
//        String url = u + "?" + param;
//        HttpGet httpGet = new HttpGet(url);
//
//        // 设置类型 "application/x-www-form-urlencoded" "application/json"
//        httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
//        System.out.println("调用URL: " + httpGet.getURI());
//
//        //        httpClient实例化
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        // 执行请求并获取返回
//        HttpResponse response = httpClient.execute(httpGet);
//        //        System.out.println("Response toString()" + response.toString());
//        HttpEntity entity = response.getEntity();
//        System.out.println("返回状态码:" + response.getStatusLine());
//
//        //得到返回数据的长度;没有该参数返回-1
//        //        if (entity != null) {
//        //            System.out.println("返回消息内容长度: " + entity.getContentLength());
//        //        }
//
//        // 显示结果
//        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
//        String line = null;
//        StringBuffer responseSB = new StringBuffer();
//        while ((line = reader.readLine()) != null) {
//            responseSB.append(line);
//        }
//        System.out.println("返回消息:" + responseSB.substring(0, 200));
//        reader.close();
//
//        httpClient.close();
//    }
//
//
//    public static String httpGet(String url, String param, String charset)
//            throws HttpException, IOException {
//        String json = null;
//        HttpGet httpGet = new HttpGet();
//        //        httpClient实例化
//        CloseableHttpClient client = HttpClients.createDefault();
//        // 设置参数
//        try {
//            httpGet.setURI(new URI(url + "?" + param));
//        } catch (URISyntaxException e) {
//            throw new HttpException("请求url格式错误。" + e.getMessage());
//        }
//        // 发送请求
//        HttpResponse httpResponse = client.execute(httpGet);
//        // 获取返回的数据
//        HttpEntity entity = httpResponse.getEntity();
//        byte[] body = EntityUtils.toByteArray(entity);
//        StatusLine sL = httpResponse.getStatusLine();
//        int statusCode = sL.getStatusCode();
//        if (statusCode == 200) {
//            json = new String(body, charset);
//            entity.consumeContent();
//        } else {
//            throw new HttpException("statusCode11111111=" + statusCode);
//        }
//        return json;
//    }


    /**
     * 发送post请求
     *
     * @param requestUrl       请求url
     * @param requestHeader    请求头
     * @param formTexts        表单数据
     * @param files            上传文件
     * @param requestEncoding  请求编码
     * @param responseEncoding 响应编码
     * @return 页面响应html
     */
    public static String sendPost(String requestUrl, Map<String, String> requestHeader, Map<String, String> formTexts, Map<String, String> files, String requestEncoding, String responseEncoding) {
        OutputStream out = null;
        BufferedReader reader = null;
        String result = "";
        try {
            if (requestUrl == null || requestUrl.isEmpty()) {
                return result;
            }
            URL realUrl = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            if (requestEncoding == null || requestEncoding.isEmpty()) {
                requestEncoding = "UTF-8";
            }
            if (responseEncoding == null || responseEncoding.isEmpty()) {
                responseEncoding = "UTF-8";
            }
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            if (files == null || files.size() == 0) {
                connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                out = new DataOutputStream(connection.getOutputStream());
                if (formTexts != null && formTexts.size() > 0) {
                    String formData = "";
                    for (Entry<String, String> entry : formTexts.entrySet()) {
                        formData += entry.getKey() + "=" + entry.getValue() + "&";
                    }
                    formData = formData.substring(0, formData.length() - 1);
                    out.write(formData.toString().getBytes(requestEncoding));
                }
            } else {
                String boundary = "-----------------------------" + String.valueOf(new Date().getTime());
                connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);
                out = new DataOutputStream(connection.getOutputStream());
                if (formTexts != null && formTexts.size() > 0) {
                    StringBuilder sbFormData = new StringBuilder();
                    for (Entry<String, String> entry : formTexts.entrySet()) {
                        sbFormData.append("--" + boundary + "\r\n");
                        sbFormData.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                        sbFormData.append(entry.getValue() + "\r\n");
                    }
                    out.write(sbFormData.toString().getBytes(requestEncoding));
                }
                for (Entry<String, String> entry : files.entrySet()) {
                    String fileName = entry.getKey();
                    String filePath = entry.getValue();
                    if (fileName == null || fileName.isEmpty() || filePath == null || filePath.isEmpty()) {
                        continue;
                    }
                    File file = new File(filePath);
                    if (!file.exists()) {
                        continue;
                    }
                    out.write(("--" + boundary + "\r\n").getBytes(requestEncoding));
                    out.write(("Content-Disposition: form-data; name=\"" + fileName + "\"; filename=\"" + file.getName() + "\"\r\n").getBytes(requestEncoding));
                    out.write(("Content-Type: application/x-msdownload\r\n\r\n").getBytes(requestEncoding));
                    DataInputStream in = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                    out.write(("\r\n").getBytes(requestEncoding));
                }
                out.write(("--" + boundary + "--").getBytes(requestEncoding));
            }
            out.flush();
            out.close();
            out = null;
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), responseEncoding));
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常!");
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


}

 //下边是调用得方式.

String path1 = "D:/";
String url = "http://10.76.153.11:8080/trainmodel?epoch=1&accessToken=" + token3;
            //设置file的name,路径
            Map<String, String> fileMap = new HashMap<>();
            fileMap.put("file1", path1+"project-nenglidiaoyong-file/usernumber.csv");
            String contentType = "";//image/png
            //调用上传文件的post请求
            String ret = HttpClientUtil.sendPost(url,null,null,fileMap,"UTF-8","UTF-8");

  • 9
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java调用post上传文件带参可以使用Apache HttpComponents库来实现,具体步骤如下: 1. 引入HttpComponents库 ```java <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` 2. 创建HttpPost请求 ```java HttpPost httpPost = new HttpPost(url); ``` 3. 创建MultipartEntityBuilder ```java MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ``` 4. 添加文件 ```java builder.addBinaryBody("file", file); ``` 5. 添加其他参 ```java builder.addTextBody("param1", "value1"); ``` 6. 构建HttpEntity ```java HttpEntity entity = builder.build(); ``` 7. 设置请求实体 ```java httpPost.setEntity(entity); ``` 8. 执行请求 ```java CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost); ``` 完整代码示例: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntityBuilder; 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; public class HttpUpload { public static void main(String[] args) { String url = "http://localhost:8080/upload"; File file = new File("test.txt"); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", file); builder.addTextBody("param1", "value1"); HttpEntity entity = builder.build(); httpPost.setEntity(entity); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost)) { HttpEntity responseEntity = response.getEntity(); System.out.println(EntityUtils.toString(responseEntity)); } catch (IOException e) { e.printStackTrace(); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值