http请求方式-HttpURLConnection
http请求方式-HttpURLConnection
import com.alibaba.fastjson.JSON;
import com.example.core.mydemo.http.OrderReqVO;
import org.springframework.lang.Nullable; import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; public class HttpURLConnectionUtil {
/*
* Http get请求
* @param httpUrl 连接
* @return 响应数据
*/
public static String doGet(String httpUrl){
//链接
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
StringBuffer result = new StringBuffer();
try {
//创建连接
URL url = new URL(httpUrl);
connection = (HttpURLConnection) url.openConnection();
//设置请求方式
connection.setRequestMethod("GET");
//设置连接超时时间
connection.setReadTimeout(15000);
//开始连接
connection.connect();
//获取响应数据
if (connection.getResponseCode() == 200) {
//获取返回的数据
is = connection.getInputStream();
if (null != is) {
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String temp = null;
while (null != (temp = br.readLine())) {
result.append(temp);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭远程连接
connection.disconnect();
}
return result.toString();
} /**
* Http post请求
* @param httpUrl 连接
* @param param 参数
* @return
*/
public static String doPost(String httpUrl, @Nullable String param) throws Exception{
StringBuffer result = new StringBuffer();
//连接
HttpURLConnection connection = null;
OutputStream os = null;
InputStream is = null;
BufferedReader br = null;
try {
//创建连接对象
URL url = new URL(httpUrl);
//创建连接
// connection = (HttpURLConnection) url.openConnection();
if(httpUrl.startsWith("https")){
trustHttps();
connection = (HttpsURLConnection) url.openConnection();
}else{
connection = (HttpURLConnection) url.openConnection();
}
//设置请求方法
connection.setRequestMethod("POST");
//设置连接超时时间
connection.setConnectTimeout(15000);
//设置读取超时时间
connection.setReadTimeout(15000);
//DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
//设置是否可读取
connection.setDoOutput(true);
connection.setDoInput(true);
//设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); //拼装参数
if (null != param && !param.equals("")) {
//设置参数
os = connection.getOutputStream();
//拼装参数
os.write(param.getBytes("UTF-8"));
}
//设置权限
//设置请求头等
//开启连接
//connection.connect();
//读取响应
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
if (null != is) {
br = new BufferedReader(new InputStreamReader(is, "GBK"));
String temp = null;
while (null != (temp = br.readLine())) {
result.append(temp);
result.append("\r\n");
}
}
} } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭连接
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭连接
connection.disconnect();
}
return result.toString();
} private static void trustHttps() throws Exception{
//第一个参数为协议,第二个参数为提供者(可以缺省)
SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
TrustManager[] tm = {new MyX509TrustManager()};
sslcontext.init(null, tm, new SecureRandom());
HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslsession) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
} public static class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override
public X509Certificate[] getAcceptedIssuers() {
return null;
} } public static void main(String[] args) {
OrderReqVO data = new OrderReqVO();
data.setOrderNum("111123333");
data.setServerType("1"); String url = "https://域名/接口名称"; String message = null;
try {
message = doPost(url, JSON.toJSONString(data));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("message = " + message);
} }
http请求方式-HttpURLConnection的更多相关文章
- Android之Http通信——3.Android HTTP请求方式:HttpURLConnection
3.Android HTTP请求方式之HttpURLConnection 引言: 好了,前两节我们已经对HTTP协议进行了学习.相信看完前两节的朋友对HTTP协议相比之前 应该更加熟悉吧.好吧.学了要 ...
- Android——JDK的get请求方式
layout文件: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:an ...
- Http请求的 HttpURLConnection 和 HttpClient
HTTP 请求方式: GET和POST的比较 请求包.png 例子.png 响应包.png 例子.png 请求头描述了客户端向服务器发送请求时使用的http协议类型,所使用的编码,以及发送内容的长度, ...
- Android进阶(一)几种网络请求方式详解
Ref:http://blog.csdn.net/zuolongsnail/article/details/6373051 Android应用经常会和服务器端交互,这就需要手机客户端发送网络请求,下面 ...
- JDK的get请求方式
package com.example.wang.testapp3; import android.app.ProgressDialog; import android.os.Bundle; impo ...
- 航信电子发票开发(servlet请求方式)
在系统用户交费后,需要打印发票,可以选择普票或者机打票(票据信息在系统中自定义设置的),也可以打印电子发票,这里对接的是航信的电子发票,请求方式非web服务,而是使用servlet通过HTTP请求的方 ...
- HTTP访问的两种方式:HttpURLConnection和HTTPClient的比较
http://blog.sina.com.cn/s/blog_87216a0001014sm7.html http://www.2cto.com/kf/201305/208770.html ----- ...
- 限制action所接受的请求方式或请求参数
原文:http://www.cnblogs.com/liukemng/p/3726897.html 2.限制action所接受的请求方式(get或post): 之前我们在HelloWorldContr ...
- 第二节(RequestMapping请求方式)学习尚硅谷-springmvc视频教程
项目中,创建测试类SpringMVCTest @Controller @RequestMapping("/springmvc1") public class SpringMVCTe ...
- jQuery中ajax的4种常用请求方式
jQuery中ajax的4种常用请求方式: 1.$.ajax()返回其创建的 XMLHttpRequest 对象. $.ajax() 只有一个参数:参数 key/value 对象,包含各配置及回调函数 ...
随机推荐
- Serverless 时代下大规模微服务应用运维的最佳实践
简介: 原来的微服务用户需要自建非常多的组件,包括 PaaS 微服务一些技术框架,运维 IaaS.K8s,还包括可观测组件等.SAE 针对这些方面都做了整体的解决方案,使用户只需要关注自己的业务系统, ...
- WPF 已知问题 Popup 吃掉 PreviewMouseDown 事件
在 WPF 中,使用 Popup 也许会看到 PreviewMouseDown 事件被吃掉 因为 PreviewMouseDown 是 RoutingStrategy.Direct 路由事件,不能在多 ...
- dotnet 使用 XWT 构建跨平台客户端 入门篇
本文告诉大家如何入门开始开发一个基于 mono 组织开源的 XWT 跨平台客户端 UI 框架的应用,本文的 xwt 是在 GitHub 上完全开源的,基于 MIT 协议的,底层采用 GTK# 的 UI ...
- kubeadm搭建单master多node节点的k8s集群(3)
一.实验环境准备 K8s集群角色 IP 主机名 安装的组件 配置 控制节点 192.168.1.10 master apiserver.controller-manager.scheduler.etc ...
- 01二分 [AGC006D] Median Pyramid Hard + P2824 [HEOI2016/TJOI2016] 排序
[AGC006D] Median Pyramid Hard 考虑对于一个长度为 2n + 1 的 01 序列 b 如何快速确定堆顶元素. _ _ _ _ x _ _ _ 0 x _ _ 0 0 x _ ...
- Web Audio API 第6章 高级主题
高级主题 这一章涵盖了非常重要的主题,但比本书的其他部分稍微复杂一些. 我们会深入对声音添加音效,完全不通过任何音频缓冲来计算合成音效, 模拟不同声音环境的效果,还有关于空 3D 空间音频. 重要理论 ...
- SAP Adobe Form 教程二 表
本文将介绍一些进阶内容,前文:SAP Adobe Form 教程一 简单示例 方法和对比 使用表对象(Table Object)创建表 优点: 它简单易行. 当我们只有很少的字段单行时,我们可以使用它 ...
- 【2023知乎爬虫】我用Python爬虫爬了2386条知乎评论!
目录 一.爬取目标 二.展示爬取结果 三.爬虫代码讲解 3.1 分析知乎页面 3.2 爬虫代码 四.同步视频 五.完整源码 您好,我是 @马哥python说,一枚10年程序猿. 一.爬取目标 前些天我 ...
- 文件上传--php user.ini详解
文件上传 参考文档:https://www.php.net/manual/zh/configuration.file.per-user.php 如果你的 PHP 以模块化运行在 Apache 里,则用 ...
- go 操作 Excel
文档地址: https://xuri.me/excelize/zh-hans/ package main import ( "fmt" "github.com/xuri/ ...