java http post图片

java http post图片文件,参考文章https://blog.csdn.net/yjclsx/article/details/70675057

 /**
     * 上传文件到指定地址URL
     *
     * @param fileName 文件名
     * @param urlStr   上传地址
     * @return
     */
    public static String uploadFile(String urlStr, String deviceId, File file) {
        try {
            // 换行符
            final String NEWLINE = "\r\n";
            final String BOUNDARY = "----brujarBoundaryari0emH33oMihIU4";

            // 服务器的上传地址
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求头参数
            conn.setRequestMethod("POST");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36");
            conn.connect();

            OutputStream out = new DataOutputStream(conn.getOutputStream());

            // 添加参数
            StringBuilder sb1 = new StringBuilder();
            sb1.append("--");
            sb1.append(BOUNDARY);
            sb1.append(NEWLINE);
            sb1.append("Content-Disposition: form-data; name=\"deviceId\"");
            sb1.append(NEWLINE);
            sb1.append(NEWLINE);
            sb1.append(deviceId);
            sb1.append(NEWLINE);
            out.write(sb1.toString().getBytes());

            // 文件参数
            StringBuilder sb = new StringBuilder();
            sb.append("--");
            sb.append(BOUNDARY);
            sb.append(NEWLINE);
            sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"");
            sb.append(NEWLINE);
            sb.append("Content-Type:application/octet-stream");
            sb.append(NEWLINE);
            sb.append(NEWLINE);
            // 将参数头的数据写入到输出流中
            out.write(sb.toString().getBytes());

            // 数据输入流,用于读取文件数据
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            byte[] bufferOut = new byte[2048];
            int bytes = 0;
            // 每次读2KB数据,并且将文件数据写入到输出流中
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            // 最后添加换行
            out.write(NEWLINE.getBytes());
            in.close();
            // 定义最后数据分隔线,即--加上BOUNDARY再加上--。
            byte[] end_data = (NEWLINE + "--" + BOUNDARY + "--" + NEWLINE).getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();
            out.close();

            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            return buffer.toString();
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常!" + e);
            e.printStackTrace();
        }
        return "";
    }


    public static void main(String[] args) {
        String url = "http://127.0.0.1:8880/api";
        String filePath = "D:\\11.jpg";
        String result = uploadFile(url, "hgfuuyitygcfyri", new File(filePath));
        System.out.println(result);
    }

打印结果,成功会返回图片预览地址,以后将屏蔽预览地址,不要做其他用途

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中使用HttpPost实现数据流方式上传图片的步骤如下: 1. 创建HttpClient对象 ```java CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 2. 创建HttpPost对象,并设置请求URL ```java HttpPost httpPost = new HttpPost("http://example.com/upload"); ``` 3. 创建HttpEntity对象,并设置上传的文件和参数 ```java MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // 设置文件参数 File file = new File("image.jpg"); entityBuilder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName()); // 设置其他参数 entityBuilder.addTextBody("name", "example"); HttpEntity httpEntity = entityBuilder.build(); httpPost.setEntity(httpEntity); ``` 4. 执行HttpPost请求,并获取响应结果 ```java CloseableHttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); String response = EntityUtils.toString(responseEntity); ``` 完整的代码示例: ```java import java.io.File; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; 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; public class ImageUploader { public static void main(String[] args) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/upload"); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // 设置文件参数 File file = new File("image.jpg"); entityBuilder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName()); // 设置其他参数 entityBuilder.addTextBody("name", "example"); HttpEntity httpEntity = entityBuilder.build(); httpPost.setEntity(httpEntity); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); String response = EntityUtils.toString(responseEntity); System.out.println(response); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值