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 对象,包含各配置及回调函数 ...
随机推荐
- [FAQ] CodeLlama GGUF 文件下载
hf-mirror: https://hf-mirror.com/TheBloke/CodeLlama-7B-GGUFmodelscope: https://modelscope.cn/models/ ...
- [FAQ] PHPStorm None project files detection
当你发现在 phpstorm 中编辑项目文件,却提示 None project files detection.. 并且左侧 Project 下面只有文件,没有项目目录了. 此时可以删除项目目录下的 ...
- [FAQ] Win10 WSL Ubuntu 根目录实际位置
1. 运行(win+R),直接输入 \\wsl$ 进入Ubuntu的目录. 2. 或者文件夹里同样输入 \\wsl$ 进行查找. Refer:Win10 WSL 路径 Link:https://ww ...
- [FE] Quasar 性能优化: 减小 vendor.js 尺寸
默认情况下,出于性能和缓存的原因,Quasar 所有来自 node_modules 的东西都会被注入到 vendor 中. 但是,如果希望从这个 vendor.js 中添加或删除某些内容,可以如下这样 ...
- WPF 笔迹触摸点收集工具
本文来安利大家一个工具,可以用来收集笔迹的触摸点,这个工具完全开源 在开始之前先看一下工具的界面 实现方式其实就在触摸的时候收集触摸点信息,上面的工具有很多功能都没有实现的.笔迹绘制的功能使用 WPF ...
- IEC104 从站/服务端模拟器 调试工具推荐
目录 IEC104 从站/服务端模拟器 调试工具推荐 主要功能 软件截图 IEC104 从站/服务端模拟器 调试工具推荐 下载地址:http://www.redisant.cn/iec104serve ...
- 使用Binlog日志恢复误删的MySQL数据实战
前言 "删库跑路"是程序员经常谈起的话题,今天,我就要教大家如何删!库!跑!路! 开个玩笑,今天文章的主题是如何使用Mysql内置的Binlog日志对误删的数据进行恢复,读完本文, ...
- [WC/CTS2024] 线段树 题解
Link 纪念一下场切题. 题意:给定一棵(分点不一定为中点)的线段树,给定若干个询问区间,问有多少个线段树上结点的集合,知道了这些结点对应的区间和就可以知道任何一个询问区间的和. 从询问区间开始考虑 ...
- python教程5:函数编程
函数编程 特性: 1.减少重复代码 2.让程序变的可扩展 3.使程序变得易维护 定义: 默认参数 要求:默认参数放在其他参数右侧 指定参数(调用的时候) 正常情况下,给函数传参数要按顺序,如果不想按 ...
- C#实现多线程的几种方式
前言 多线程是C#中一个重要的概念,多线程指的是在同一进程中同时运行多个线程的机制.多线程适用于需要提高系统并发性.吞吐量和响应速度的场景,可以充分利用多核处理器和系统资源,提高应用程序的性能和效率. ...