JDK发送Http请求


        HttpURLConnection conn = null;
        InputStream is = null;
        BufferedReader reader = null;
        String msg;
        try {
            String sClientVersion = String.valueOf(clientVersion);
            httpUrl = MessageFormat.format(httpUrl, sClientVersion,Prop.provinceId);
            URL url = new URL(httpUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "close");
            conn.connect();
            int resCode = conn.getResponseCode();
            if (resCode == HttpURLConnection.HTTP_OK) {
                is = conn.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sb = new StringBuffer();
                String strRead = null;
                while ((strRead = reader.readLine()) != null) {
                    sb.append(strRead);
                }
                msg = sb.toString();
                JSONObject jobj = JSONObject.fromObject(msg);

                String returnCode = (String) jobj.get("returnCode");
                if ("0".equals(returnCode)) {
                    JSONArray arry = JSONArray.fromObject(jobj.get("object"));
                    List<PromptFile> lis = JSONArray.toList(arry, PromptFile.class);
                    logger.info("获取版本变化成功! :  "+lis);
                    return lis;
                }else{
                    logger.info("获取版本变化失败! : recutnCode 不等于0 !");
                    throw new Exception("获取版本变化失败! :  returnCode:"+returnCode);
                }
            } else {
                msg = URLDecoder.decode(conn.getResponseMessage(), "UTF-8");
                logger.info("resCode : "+resCode);
                throw new Exception("获取最新版本失败 : responseCode"+resCode+" returnMessage:"+msg);
            }
        } catch (IOException e) {
            throw new Exception("获取版本变化失败,连接业务运营系统失败", e);
        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(is);
            if (conn != null) {
                conn.disconnect();
            }
        }
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java 17中,发送HTTP请求并附带文件通常使用HttpURLConnection、HttpClient或者第三方库如Apache HttpClient或OkHttp。这里我们以HttpURLConnection为例,因为它是Java内置的网络客户端: ```java import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class FileUploadExample { private static final String FILE_PATH = "path/to/your/file.txt"; // 替换为你的文件路径 private static final String UPLOAD_URL = "http://example.com/upload"; // 替换为你的服务器上传地址 public static void main(String[] args) throws Exception { URL url = new URL(UPLOAD_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"); // 添加文件到请求 String boundary = "--" + connection.getHeaderField("Content-Type").split("="); try (FileInputStream fis = new FileInputStream(new File(FILE_PATH)); OutputStream os = connection.getOutputStream()) { byte[] buffer = new byte[1024]; int read; while ((read = fis.read(buffer)) != -1) { os.write(boundary.getBytes()); os.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + FILE_PATH + "\"\r\n").getBytes()); os.write("Content-Type: application/octet-stream\r\n\r\n".getBytes()); os.write(buffer, 0, read); os.write("\r\n".getBytes()); } os.write("--" + boundary + "--\r\n".getBytes()); // 设置请求完成后再关闭流 fis.close(); } // 获取响应状态码和结果 int responseCode = connection.getResponseCode(); System.out.println("Response Code : " + responseCode); // 关闭连接 connection.disconnect(); } } ``` 注意:在实际生产环境中,你可能需要处理异常,比如文件读取错误、网络连接错误等。此外,如果你需要更高级的功能,例如断点续传、进度跟踪等,建议使用第三方库,它们通常提供更完善的功能和更好的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值