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的更多相关文章

  1. Android之Http通信——3.Android HTTP请求方式:HttpURLConnection

    3.Android HTTP请求方式之HttpURLConnection 引言: 好了,前两节我们已经对HTTP协议进行了学习.相信看完前两节的朋友对HTTP协议相比之前 应该更加熟悉吧.好吧.学了要 ...

  2. Android——JDK的get请求方式

    layout文件: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:an ...

  3. Http请求的 HttpURLConnection 和 HttpClient

    HTTP 请求方式: GET和POST的比较 请求包.png 例子.png 响应包.png 例子.png 请求头描述了客户端向服务器发送请求时使用的http协议类型,所使用的编码,以及发送内容的长度, ...

  4. Android进阶(一)几种网络请求方式详解

    Ref:http://blog.csdn.net/zuolongsnail/article/details/6373051 Android应用经常会和服务器端交互,这就需要手机客户端发送网络请求,下面 ...

  5. JDK的get请求方式

    package com.example.wang.testapp3; import android.app.ProgressDialog; import android.os.Bundle; impo ...

  6. 航信电子发票开发(servlet请求方式)

    在系统用户交费后,需要打印发票,可以选择普票或者机打票(票据信息在系统中自定义设置的),也可以打印电子发票,这里对接的是航信的电子发票,请求方式非web服务,而是使用servlet通过HTTP请求的方 ...

  7. HTTP访问的两种方式:HttpURLConnection和HTTPClient的比较

    http://blog.sina.com.cn/s/blog_87216a0001014sm7.html http://www.2cto.com/kf/201305/208770.html ----- ...

  8. 限制action所接受的请求方式或请求参数

    原文:http://www.cnblogs.com/liukemng/p/3726897.html 2.限制action所接受的请求方式(get或post): 之前我们在HelloWorldContr ...

  9. 第二节(RequestMapping请求方式)学习尚硅谷-springmvc视频教程

    项目中,创建测试类SpringMVCTest @Controller @RequestMapping("/springmvc1") public class SpringMVCTe ...

  10. jQuery中ajax的4种常用请求方式

    jQuery中ajax的4种常用请求方式: 1.$.ajax()返回其创建的 XMLHttpRequest 对象. $.ajax() 只有一个参数:参数 key/value 对象,包含各配置及回调函数 ...

随机推荐

  1. 阿里云 Serverless 助力企业全面拥抱云原生

    ​简介:相信随着云计算的发展,Serverless 将成为云时代默认的计算范式,越来越多的企业客户将会采用这个技术. 作者:洛浩 Serverless 应用引擎的组件架构 最早的时候,大家设计软件一般 ...

  2. 实时数仓入门训练营:基于 Apache Flink + Hologres 的实时推荐系统架构解析

    ​ 简介: <实时数仓入门训练营>由阿里云研究员王峰.阿里云资深技术专家金晓军.阿里云高级产品专家刘一鸣等实时计算 Flink 版和 Hologres 的多名技术/产品一线专家齐上阵,合力 ...

  3. [ML] 通过llama.cpp与羊驼聊天的网页界面- 详解 Serge 的启动使用

      Serge 虽然能够让我们在笔记本上跑起来 7B模型, 但实际运行非常消耗CPU,对话生成响应非常非常慢. 1. 官方指导是使用如下命令直接运行: $ docker run -d -v weigh ...

  4. [FAQ] Goland 始终没有包代码的提示 ?

    表现:import 引入的包始终是红色的,表示没有找到引入的包. 注意,在这里开启Go Modules: 然后在 Exteneral Libraries 里看到 Go Modules 即可. Refe ...

  5. dotnet 6 数组拷贝性能对比

    本文来对比多个不同的方法进行数组拷贝,和测试其性能 测试性能必须采用基准(标准)性能测试方法,否则测试结果不可信.在 dotnet 里面,可以采用 BenchmarkDotNet 进行性能测试.详细请 ...

  6. LabView之MQTT协议使用

    一.MQTT概述 MQTT协议是一种消息列队传输协议,采用订阅.发布机制,订阅者只接收自己已经订阅的数据,非订阅数据则不接收,既保证了必要的数据的交换,又避免了无效数据造成的储存与处理.因此在工业物联 ...

  7. 记录几十页html生成pdf的历程和坑(已用bookjs-easy解决)(生成、转换、拼接pdf)

    懒得看的朋友,先说最终解决办法,主力为 前端依靠插件 bookjs-easy(点击直接跳转官网)并跳转到下面的第三点查看 接下来详细记录下整个试探的方向和历程 项目需求:是生成一个页数达到大几十页的p ...

  8. 在IDEA中配置GitHub

    目录 在IDEA中配置GitHub 安装GitHub插件 账号授权 方法一:点击Add Account... 添加账号 方法二:使用token登录 共享到GitHub 查看文件变更列表 add文件 移 ...

  9. Selenium4自动化测试2--元素定位By.ID,By.CLASS_NAME,By.TAG_NAME

    三.元素定位方式 1-通过id定位,By.ID id属性在HTML中是唯一的,因此使用id定位可以确保找到页面上唯一的元素. 由于id是唯一的,浏览器在查找元素时可以快速定位到目标元素,提高了定位的效 ...

  10. cesium介绍和国内主要学习网站汇总

    Cesium官方网站 建议大家将Cesium官网的博客都读一遍,博客大概分为三类,主要是技术类,比如性能优化,调度算法等,一类是定期的新版本特性,能够了解Cesium新功能和新特性,还有一类是大事记, ...