Java工具类_模拟HTTP POST请求
2024-09-23 09:48:03
import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpPostTest { public static void main(String[] args) throws Exception { //请求数据【加密】 String netPoint = "JTNDJTNGeG1sK3ZQyUyRmh0dHBBcGklM0UlMEE="; //Xml或json格式 netPoint = "{ \"userName\": \"01404673\" }"; netPoint = "<userName>01404673</userName>"; //请求地址[ 本地 ] String strurl = "http://127.0.0.1:8080/hop/order/getForwardConfirmToAccountCenter?app_key=1201&secret=927666f2"; URL url = new URL(strurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5 * 1000);//设置超时的时间 conn.setDoInput(true); conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据 conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); conn.setRequestProperty("Content-Length", String.valueOf(netPoint.length())); conn.addRequestProperty("Authorization", "Basic ZWhhaWVyMjAxMTplaGFpZXImMmFiKihf"); conn.connect(); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(netPoint.getBytes("UTF-8"));//写入请求的字符串 out.flush(); out.close(); //请求返回的状态 if (conn.getResponseCode() == 200) { //请求返回的数据 byte[] datas = readInputStream(conn.getInputStream()); //转成字符串 String responseMsg = new String(datas, "utf-8"); System.out.println("返回数据:\n" + responseMsg); //将返回数据写入文件 // File dest = new File("D:\\abc.txt"); // InputStream is = new ByteArrayInputStream(responseMsg.getBytes()); // OutputStream os = new FileOutputStream(dest); // byte[] flush = new byte[1024]; // int len = 0; // // while (-1 != (len = is.read(flush))) { // os.write(flush, 0, len); // } // // os.flush(); // os.close(); // is.close(); } else { System.out.println("请求失败:\n code:" + conn.getResponseCode() + "\n msg:" + conn.getResponseMessage()); } //关闭连接 conn.disconnect(); } private static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } byte[] data = outStream.toByteArray();//二进制数据 return data; } finally { outStream.close(); inStream.close(); } } }
最新文章
- SQL Server高级查询
- 一张图说明CDN网络的原理
- zepto和jquery的区别,zepto的不同使用8条小结
- spring容器加载完毕做一件事情(利用ContextRefreshedEvent事件)转
- HDU4812 D Tree(树的点分治)
- Activity(一)
- Android动画 interpolator的用法
- ajax 请求
- iOS: 学习笔记, Swift运算符定义
- web安全之SQL注入
- Dubbo入门—搭建一个最简单的Demo框架
- .Net语言 APP开发平台——Smobiler学习日志:如何调用API进行短信发送
- SAP MM MI01事务代码里的批次确定
- MySQL学习9 - 单表查询
- python3读取sqlyog配置文件中的MySql密码
- 【vue】使用el-table时,实现批量选中效果
- servlet生成验证码代码
- 树莓派无显示器开启ssh的方法
- CSS网页布局中易犯的30个小错误
- scala中隐式转换之隐式转换调用类中本不存在的方法