java 使用post请求发送文件

开始,使用下面方法也可以发送,但是MultipartEntity和DefaultHttpClient的创建方法都过时了,所以使用下面方法进行代替。

public static String sendPost(String urlString, java.io.File file) {
        String result = "";
        try {
            if (file.exists()) {
                HttpClient client = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost(urlString);
                MultipartEntity entity = new MultipartEntity();
                entity.addPart("file", new FileBody(file));

                httpPost.setEntity(entity);
                HttpResponse response = client.execute(httpPost);

                HttpEntity responseEntity = response.getEntity();
                result = EntityUtils.toString(responseEntity);
                System.out.println(result);
            }
        } catch (Exception e) {
            Log.error("发送POST请求出现异常!", e);
        }
        return result.toString();
    }

一、使用MultipartEntityBuilder,引入加入包仅供参考(可能少,可能多部分)

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public static String sendPost(String urlString, java.io.File file) {
        String result = null;
        CloseableHttpClient client = HttpClients.createDefault();
        HttpResponse response = null;
        try {
            if (file.exists()) {
                HttpPost httpPost = new HttpPost(urlString);
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.addBinaryBody(
                        "file",
                        new FileInputStream(file),
                        ContentType.APPLICATION_OCTET_STREAM,
                        file.getName()
                );
                HttpEntity entity = builder.build();// 生成 HTTP POST 实体
                httpPost.setEntity(entity);
                response = client.execute(httpPost);
                result = StreamUtils.copyToString(response.getEntity().getContent(), Charset.forName("UTF-8"));
                System.out.println(result);
            }
        } catch (Exception e) {
            result = e.getMessage();
            Log.error("发送POST请求出现异常!", e);
        }
        return result;
    }

二、java post请求,直接发送二进制文件(木有测试,供参考)

public static String sendPost(String urlString, byte[] bytes) {
        StringBuffer result = new StringBuffer();
        try {
            OutputStream out = null;
            InputStream in = null;
            DataOutputStream outWrite = null;
            InputStreamReader inReader = null;
            BufferedReader buffReader = null;
            String line = "";
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //post请求
            conn.setRequestMethod("POST");
            //连接超时、读取超时。防止请求被阻塞
            conn.setConnectTimeout(6000);
            conn.setReadTimeout(6000);
            //是否从httpUrlConnection读入,默认为false,当为post请求时需要设置为true
            //post的请求参数在http正文中,get的请求参数在url后
            conn.setDoOutput(true);
            //是否向httpUrlConnection输出,默认为true
            conn.setDoInput(true);
            //二进制数据
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            //缓存
            conn.setUseCaches(false);
            try {
                out = conn.getOutputStream();
                outWrite = new DataOutputStream(out);
                outWrite.write(bytes);
                outWrite.flush();
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    in = conn.getInputStream();
                } else {
                    in = conn.getErrorStream();
                }
                buffReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                while ((line = buffReader.readLine()) != null) {
                    result.append(line);
                }
            } finally {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            }
        } catch (Exception e) {
            Log.error("发送POST请求出现异常!", e);
        }
        return result.toString();
    }

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java使用HttpClient发送POST请求并上传文件流的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; 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.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.Map; public class HttpUtil { public static String postFile(String url, Map<String, String> params, Map<String, File> files) throws IOException { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 设置请求参数 for (Map.Entry<String, String> entry : params.entrySet()) { builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.create("text/plain", Charset.forName("UTF-8")))); } // 设置文件流 for (Map.Entry<String, File> entry : files.entrySet()) { builder.addPart(entry.getKey(), new FileBody(entry.getValue())); } HttpEntity entity = builder.build(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8")); EntityUtils.consume(responseEntity); return result; } } ``` 使用示例: ```java Map<String, String> params = new HashMap<>(); params.put("param1", "张三"); Map<String, File> files = new HashMap<>(); files.put("file1", new File("path/to/file1")); files.put("file2", new File("path/to/file2")); String result = HttpUtil.postFile("http://example.com/upload", params, files); System.out.println(result); ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值