HttpURLConnection

   /**
     * 接口地址
     */
    private static String POST_URL = "http://localhost:88/router/rest";
    
    /**
     * post请求
     * @param url
     * @param param
     * @return
     */
    public static Map<String, String> sendPost(String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        Integer responseCode = null;
        try {
            URL realUrl = new URL(POST_URL);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            //获取返回状态码,并根据状态码获取输入流
            InputStream is;
            responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                is = conn.getInputStream();
            } else {
                is = conn.getErrorStream();
            }
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(is));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.info("发送post请求异常:"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        Map<String, String> resultMap = new HashMap<String, String>();
        resultMap.put("responseCode", responseCode.toString());
        resultMap.put("result", result);
        return resultMap;
    }  

 

转载于:https://www.cnblogs.com/xiaoQ0725/p/9811236.html

### Java 中 `HttpURLConnection` 的使用方法 #### 1. 基本概念 `HttpURLConnection` 是 Java 提供的一个用于执行 HTTP 请求的类。它允许开发者通过 URL 对象建立连接并发送 GET、POST 等类型的请求[^3]。 #### 2. 创建连接 要创建一个基于 `HttpURLConnection` 的 HTTP 连接,通常需要以下几个步骤: - 将目标地址封装成 `URL` 对象。 - 调用 `openConnection()` 方法获取到 `HttpURLConnection` 实例。 以下是基本代码示例: ```java import java.net.HttpURLConnection; import java.net.URL; public class HttpExample { public static void main(String[] args) throws Exception { String urlString = "http://example.com"; URL url = new URL(urlString); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // 设置请求方式 int responseCode = conn.getResponseCode(); // 获取响应码 System.out.println("Response Code: " + responseCode); conn.disconnect(); // 断开连接 } } ``` 上述代码展示了如何打开一个简单的 HTTP GET 请求,并打印服务器返回的状态码[^1]。 #### 3. 发送 POST 请求 如果需要向服务器提交数据,则可以设置请求头以及写入请求体的内容。下面是一个完整的 POST 请求示例: ```java import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class PostRequestExample { public static void main(String[] args) throws Exception { String urlString = "http://example.com/api"; URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); // 启用输出流 conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); try(OutputStream os = conn.getOutputStream()) { // 写入 JSON 数据 byte[] input = "{\"key\":\"value\"}".getBytes("utf-8"); os.write(input, 0, input.length); } int responseCode = conn.getResponseCode(); System.out.println("Post Response Code : " + responseCode); conn.disconnect(); } } ``` 此代码片段演示了如何构建带有 JSON 数据的 POST 请求。 #### 4. 处理常见问题 ##### (1)超时设置 为了避免因网络延迟而导致程序卡住的情况,可以通过以下两个参数来设定读取和连接的时间限制: ```java conn.setConnectTimeout(5000); // 单位毫秒 conn.setReadTimeout(5000); ``` ##### (2)Android 版本兼容性 对于 Android 平台而言,在版本 2.3 及以上推荐优先选用 `HttpURLConnection` 替代已废弃的 `Apache HttpClient` 库[^2]。 ##### (3)重定向处理 默认情况下,`HttpURLConnection` 不会自动跟随 HTTP 重定向(状态码 3xx)。若希望支持该功能,需手动启用: ```java conn.setInstanceFollowRedirects(true); ``` #### 总结 综上所述,`HttpURLConnection` 是一种强大而灵活的方式来进行 HTTP 操作。尽管其配置过程可能稍显复杂,但它提供了足够的控制力去满足大多数应用场景的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值