通过HttpURLConnection使用URL获取网页返回的内容

URL l_url = new URL( "网页地址");
   HttpURLConnection l_connection = (HttpURLConnection) l_url
     .openConnection();
   l_connection.connect();
   InputStream l_urlStream = l_connection.getInputStream();

//接受并转码(很重要,不然会乱码)
    BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream,"utf-8"));
   String sCurrentLine = "";
   String sTotalString = "";
   while ((sCurrentLine = l_reader.readLine()) != null)

   {
    sTotalString += sCurrentLine; 
   }

//sTotalString 就是网页返回的值

System.out.println(sTotalString );

//关闭链接
   l_reader.close();

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 `HttpURLConnection` 获取 API 的响应,可以按照以下步骤进行操作: 1. 创建 `URL` 对象,指定要请求的 API 的 URL: ```java URL url = new URL("https://api.example.com/endpoint"); ``` 2. 打开连接并设置请求方法为 GET(或其他适当的方法): ```java HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); ``` 3. 如果需要设置请求头,可以使用 `setRequestProperty` 方法添加请求头参数: ```java connection.setRequestProperty("Content-Type", "application/json"); ``` 4. 发送请求,并获取响应状态码: ```java int responseCode = connection.getResponseCode(); ``` 5. 根据响应状态码判断请求是否成功: ```java if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功,读取响应内容 InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 处理响应内容 System.out.println(response.toString()); } else { // 请求失败,根据需要处理错误 System.out.println("请求失败,错误码:" + responseCode); } ``` 6. 最后,记得关闭连接: ```java connection.disconnect(); ``` 以上是使用 `HttpURLConnection` 获取 API 响应的基本步骤。你可以根据需要调整和扩展代码来适应不同的场景和要求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值