Java:HttpURLConnection发送GET和POST请求
发布日期:2021-07-01 06:11:16
浏览次数:2
分类:技术文章
本文共 2461 字,大约阅读时间需要 8 分钟。
发送GET请求
package demo;import java.io.*;import java.net.HttpURLConnection;import java.net.URL;public class HttpDemo { public static void main(String[] args) throws IOException { String url = "https://www.baidu.com/"; // 得到connection对象 URL httpUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection(); //连接 connection.connect(); // 获取状态码 响应结果 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); System.out.println(buffer.toString()); } // 断开连接 connection.disconnect(); }}
发送POST请求
package demo;import java.io.*;import java.net.HttpURLConnection;import java.net.URL;public class HttpDemo { public static void main(String[] args) throws IOException { String url = "http://httpbin.org/post"; //得到connection对象 URL httpUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection(); //设置请求方式 connection.setRequestMethod("POST"); connection.setDoOutput(true); // 设置请求头 connection.setRequestProperty("Accept", "*/*"); // 设置请求体 String body = "name=Tom&age=23"; OutputStream outputStream = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); writer.write(body); writer.close(); //连接 connection.connect(); // 获取状态码 响应结果 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); System.out.println(buffer.toString()); } // 断开连接 connection.disconnect(); }}
转载地址:https://pengshiyu.blog.csdn.net/article/details/106730674 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
逛到本站,mark一下
[***.202.152.39]2024年04月14日 00时03分22秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
python import midi error
2019-05-07
MyBatis模糊查询的sql拼接
2019-05-07
CSS选择器
2019-05-07
cocos2d-x auto-batching
2019-05-07
cocos-lua 使用plist文件
2019-05-07
gitlab迁移后一直提示413错误
2019-05-07
ElasticSearch查询语句概述
2019-05-07
springboot 数据连接池HikariPool
2019-05-07
基于角色得后台权限管理系统设计(一、表设计)
2019-05-07
maven得一些知识点
2019-05-07
Spark集成Kafka源码分析——SparkStreaming从kafak中接收数据
2019-05-07
安装Redis
2019-05-07
Java 全角、半角字符转化
2019-05-07
即兴编程: 如何通过编程表达个人情感
2019-05-07
Leetcode 删除排序链表中的重复元素
2019-05-07
Leetcode 买卖股票的最佳时机
2019-05-07
服务器修改端口
2019-05-08
1 基于图灵机器人的对话
2019-05-08