当前位置: 首页 > news >正文

用HttpURLConnection复现http响应码405

目录

  • 使用GET方法,访问GET接口,服务端返回405
  • 使用GET方法,访问POST接口,服务端返回405
  • 使用POST方法,访问GET接口,服务端返回405

使用GET方法,访问GET接口,服务端返回405

发生场景:
复制的POST请求代码,手动修改为GET,没有修改彻底,导致错误。

错误代码:

public class GET405 {public static void main(String[] args) {try {String defURL = "https://httpbin.org/get";URL url = new URL(defURL);// 打开和URL之间的连接HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setRequestMethod("GET");//请求get方式con.setDoInput(true);// 默认值为 truecon.setDoOutput(true);//默认值为 false,传body参数必须写// 得到请求的输出流对象OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");String body = "username=xiaohu&password=123456";writer.write(body);writer.flush();//            System.out.println("http请求方法:"+con.getRequestMethod());System.out.println("http状态码:" + con.getResponseCode());// 获取服务端响应,通过输入流来读取URL的响应InputStream is = con.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuffer sbf = new StringBuffer();String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("\r\n");}reader.close();// 关闭连接con.disconnect();// 打印读到的响应结果System.out.println("运行结束:" + sbf.toString());} catch (Exception e) {e.printStackTrace();}}
}

报错log:

405原因:
con.getOutputStream() 会把原有的GET方法改为POST方法,用POST方法访问GET接口,就报错405。看jdk1.8中HttpURLConnection的getOutpuStream()方法的源码:

解决办法:删掉getOutputStream(),用url传参。

正确代码:

public class GET200 {public static void main(String[] args) {try {String defURL = "https://httpbin.org/get";String body = "username=xiaohu&password=123456";URL url = new URL(defURL+"?"+body);// 打开和URL之间的连接HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setRequestMethod("GET");//请求get方式//          System.out.println("http请求方法:"+con.getRequestMethod());System.out.println("http状态码:" + con.getResponseCode());// 获取服务端响应,通过输入流来读取URL的响应InputStream is = con.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuffer sbf = new StringBuffer();String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("\r\n");}reader.close();// 关闭连接con.disconnect();// 打印读到的响应结果System.out.println("运行结束:" + sbf.toString());} catch (Exception e) {e.printStackTrace();}}
}

运行结果:

http状态码:200
运行结束:{"args": {"password": "123456", "username": "xiaohu"}, "headers": {"Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2", "Host": "httpbin.org", "User-Agent": "Java/1.8.0_221", "X-Amzn-Trace-Id": "Root=1-668a1ba0-278338c97b93d6ca4276c0b0"}, "origin": "113.57.25.151", "url": "https://httpbin.org/get?username=xiaohu&password=123456"
}

使用GET方法,访问POST接口,服务端返回405

发生场景:接口文档显示接口为GET接口,实际上后端人员写的是POST接口,文档没同步。

错误代码:

public class GETtoPOST405 {public static void main(String[] args) {try {String defURL = "https://httpbin.org/post";String body="username=xiaohu&password=123456";URL url = new URL(defURL + "?" + body);HttpURLConnection con = (HttpURLConnection) url.openConnection();
//          con.setUseCaches(false); // Post请求不能使用缓存con.setRequestMethod("GET");//请求get方式con.setDoInput(true);// 设置是否从HttpURLConnection输入,默认值为 truecon.setDoOutput(false);// 设置是否使用HttpURLConnection进行输出,默认值为 falseint code = con.getResponseCode();System.out.println("http状态码:" + code);if (code == HttpURLConnection.HTTP_OK) {System.out.println("测试成功");} else {System.out.println("测试失败:" + code);}// 获取服务端响应,通过输入流来读取URL的响应InputStream is = con.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuffer sbf = new StringBuffer();String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("\r\n");}reader.close();// 关闭连接con.disconnect();// 打印读到的响应结果System.out.println("运行结束:" + sbf.toString());} catch (Exception e) {e.printStackTrace();}}
}

报错log:

http状态码:405
测试失败:405Caused by: java.io.IOException: Server returned HTTP response code: 405 for URL: https://httpbin.org/post?username=xiaohu&password=123456

405原因:不知道后端接口的定义,或者没有沟通彻底,或者后端开发人员失误,本应该是GET定义成了POST。应该使用POST方法。

解决方法:使用POST请求。

正确代码:

public class POSTtoPOST200 {public static void main(String[] args) {try {String defURL = "https://httpbin.org/post";URL url = new URL(defURL);HttpURLConnection con = (HttpURLConnection) url.openConnection();
//          con.setUseCaches(false); // Post请求不能使用缓存con.setRequestMethod("POST");//请求POST方式con.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出,默认值为 falseOutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");String body = "username=xiaohu&password=123456";writer.write(body);writer.flush();int code = con.getResponseCode();System.out.println("http状态码:" + code);if (code == HttpURLConnection.HTTP_OK) {System.out.println("测试成功");} else {System.out.println("测试失败:" + code);}// 获取服务端响应,通过输入流来读取URL的响应InputStream is = con.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuffer sbf = new StringBuffer();String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("\r\n");}reader.close();// 关闭连接con.disconnect();// 打印读到的响应结果System.out.println("运行结束:" + sbf.toString());} catch (Exception e) {e.printStackTrace();}}
}

运行结果:

http状态码:200
测试成功
运行结束:{"args": {}, "data": "", "files": {}, "form": {"password": "123456", "username": "xiaohu"}, "headers": {"Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2", "Content-Length": "31", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "Java/1.8.0_221", "X-Amzn-Trace-Id": "Root=1-668a2091-2a64856935929fab74082ce4"}, "json": null, "origin": "113.57.25.151", "url": "https://httpbin.org/post"
}

使用POST方法,访问GET接口,服务端返回405

发生场景:代码失误,本该写GET,写成了POST。

错误代码:

public class POSTtoGET405 {public static void main(String[] args) {try {String defURL = "https://httpbin.org/get";URL url = new URL(defURL);// 打开和URL之间的连接HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setRequestMethod("POST");//请求post方式
//            con.setUseCaches(false); // Post请求不能使用缓存con.setDoInput(true);// 设置是否从HttpURLConnection输入,默认值为 truecon.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出,默认值为 falseOutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");String body = "username=xiaohu&password=123456";writer.write(body);writer.flush();writer.close();int code = con.getResponseCode();System.out.println("http状态码:" + code);if (code == HttpURLConnection.HTTP_OK) {System.out.println("测试成功");} else {System.out.println("测试失败:" + code);}// 获取服务端响应,通过输入流来读取URL的响应InputStream is = con.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuffer sbf = new StringBuffer();String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("\r\n");}reader.close();// 关闭连接con.disconnect();// 打印读到的响应结果System.out.println("运行结束:" + sbf.toString());} catch (Exception e) {e.printStackTrace();}}
}

405原因: 接口只接受GET方法,请求是POST方法。

错误场景:后端开发定义失误,本该是POST接口,写成了GET。接口没有测试。

解决办法:用GET访问。正确代码和GET访问GET一样。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 【记录】LaTex|LaTex 代码片段 Listings 添加带圆圈数字标号的箭头(又名 LaTex Tikz 库画箭头的简要介绍)
  • 【深度学习基础】MacOS PyCharm连接远程服务器
  • 小白学webgl合集-Three.js加载器
  • nginx的重定向
  • 【Windows】实现窗口子类化(基于远程线程注入)
  • QImage显示图片像素
  • 技术文件国产化准备
  • [C++] 轻熟类和对象
  • 内网信息收集:手动、脚本和工具查IP、端口
  • 5-3.损失函数
  • Docker 日志丢失 - 解决方案
  • Python基于you-get下载网页上的视频
  • scipy库中,不同应用滤波函数的区别,以及FIR滤波器和IIR滤波器的区别
  • Perl 数据类型
  • 【RHCE】转发服务器实验
  • 【跃迁之路】【669天】程序员高效学习方法论探索系列(实验阶段426-2018.12.13)...
  • Android Volley源码解析
  • IP路由与转发
  • JavaScript 基础知识 - 入门篇(一)
  • Java应用性能调优
  • laravel with 查询列表限制条数
  • Spark VS Hadoop:两大大数据分析系统深度解读
  • spark本地环境的搭建到运行第一个spark程序
  • 工作手记之html2canvas使用概述
  • 欢迎参加第二届中国游戏开发者大会
  • 机器学习中为什么要做归一化normalization
  • 前端之React实战:创建跨平台的项目架构
  • 设计模式走一遍---观察者模式
  • 想写好前端,先练好内功
  • 在Unity中实现一个简单的消息管理器
  • 怎样选择前端框架
  • MiKTeX could not find the script engine ‘perl.exe‘ which is required to execute ‘latexmk‘.
  • 3月7日云栖精选夜读 | RSA 2019安全大会:企业资产管理成行业新风向标,云上安全占绝对优势 ...
  • JavaScript 新语法详解:Class 的私有属性与私有方法 ...
  • RDS-Mysql 物理备份恢复到本地数据库上
  • ​如何使用ArcGIS Pro制作渐变河流效果
  • # Redis 入门到精通(七)-- redis 删除策略
  • ### RabbitMQ五种工作模式:
  • #QT 笔记一
  • $(selector).each()和$.each()的区别
  • (1)Nginx简介和安装教程
  • (C语言)逆序输出字符串
  • (delphi11最新学习资料) Object Pascal 学习笔记---第2章第五节(日期和时间)
  • (SERIES12)DM性能优化
  • (Spark3.2.0)Spark SQL 初探: 使用大数据分析2000万KF数据
  • (免费领源码)Java#ssm#MySQL 创意商城03663-计算机毕业设计项目选题推荐
  • (实战篇)如何缓存数据
  • (贪心) LeetCode 45. 跳跃游戏 II
  • (转)socket Aio demo
  • . NET自动找可写目录
  • .equals()到底是什么意思?
  • .NET6 命令行启动及发布单个Exe文件
  • .NetCore发布到IIS
  • .NET是什么
  • .NET微信公众号开发-2.0创建自定义菜单