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. 【视频特辑】提效神器!如何用Quick BI高效配置员工的用数权限

    ​简介:随着企业数字化进程逐步加速,企业所产生和积累的数据资源日益增多.每当员工的用数权限发生变动,管理员都需要进行复杂繁琐的重复性配置流程,不仅耗时耗力还容易出错. 如何能便捷地对员工用数权限进行高 ...

  2. ARMv9刷屏 —— 号称十年最大变革,Realm机密计算技术有什么亮点?

    ​简介: 让我们看下ARMv9机密计算相关的新特性Realm. ​ ARMv9的新闻刷屏了.ARMv9号称十年以来最重大变革,因此让我们看下ARMv9中机密计算相关的新特性Realm.(注:本文是对I ...

  3. WPF开源轻便、快速的桌面启动器

    前言 今天大姚给大家分享一款WPF开源.简单.轻便.快速的桌面启动器(支持多主题.多语言:简体中文.繁体中文.英文等):CurvaLauncher. WPF介绍 WPF 是一个强大的桌面应用程序框架, ...

  4. [GPT] 神经网络模型方面的课程、神经网络模型与深度学习

      现在有很多关于神经网络模型的课程.以下是一些比较受欢迎的神经网络模型课程: Stanford CS231n:卷积神经网络(CNNs)课程 Deep Learning Specialization: ...

  5. [Go] freecache 设置 SetGCPercent 的作用

    你需要对 freecache 有一个大致了解,freecache 的内存空间是预分配的. 假设你的程序占用了 50M 内存,那么开启 freecache 预分配 200M 空间,总共下来就是 250M ...

  6. dotnet 读 WPF 源代码 聊聊 DispatcherTimer 的实现

    本文来告诉大家在 WPF 框架里面,是如何实现 DispatcherTimer 的功能.有小伙伴告诉我,读源代码系列的博客看不动,原因是太底层了.我尝试换一个方式切入逻辑,通过提问题和解决问题的方法, ...

  7. WPF 实现自定义的笔迹橡皮擦

    本文来告诉大家使用比较底层的方法来实现 WPF 的笔迹橡皮擦 在 WPF 里面,对于笔迹来说,应该放在 Stroke 类里面,而不是作为点的集合存储.在 Stroke 类里面将作为管理笔迹的类提供笔迹 ...

  8. 网站访问速度优化实战:CDN源/Nginx压缩/全站CDN加速

    前言 接触到CDN的起因: 我自己搭建的网站https://price.monitor4all.cn/网页打开的速度一直比较慢,经查证是我的网站有很多静态js大文件,通过浏览器读取这些js比较耗时间. ...

  9. zabbix API笔记

    python简单demo 输出id为111主机的主机群组信息 import requests import json request_headers = {"Content-Type&quo ...

  10. 一键入门到精通:sd-webui-prompt-all-in-one 项目大揭秘!

    今天向大家推荐一个宝藏项目.在创意无限的AI艺术生成世界中,sd-webui-prompt-all-in-one 项目如一股清流,为广大创作者和开发者带来了前所未有的便捷和灵感.这不仅仅是一个项目,它 ...