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. dotnet 使用 windbg 运行脚本方式自动批量调试处理 dump 文件

    本文将和大家介绍一个简单且实际用途不大的使用 windbg 配合脚本的方式,进行自动化的大批量对 dotnet 系应用的 dump 进行自动化分析调试处理,可以自动根据调试需求输出 dump 文件的一 ...

  2. 阿里云OSS文件上传几种方法(主要是前端)

    目录 零.准备 一.服务端签名后直传 1. 阿里云控制台配置 2. 后端接口开发(PHP) 3. 前端获取签名后上传 二.使用STS临时凭证进行上传 1. 后端接口开发(node) 2. 前端获取临时 ...

  3. 如何将data中字符传的换行正常显示

    后端传来的字符串有换行符: 直接输出的效果: 解决方法demo: <p class="" v-html="text"></p> js: ...

  4. SpringBoot项目预加载数据——ApplicationRunner、CommandLineRunner、InitializingBean 、@PostConstruct区别

    0.参考.业务需求 参考: https://www.cnblogs.com/java-chen-hao/p/11835120.html#_label1 https://zhuanlan.zhihu.c ...

  5. Winform项目中纯代码创建WCF服务

    接口: [ServiceContract(CallbackContract = typeof(IViewCallback), SessionMode = SessionMode.Required)] ...

  6. blazor中的PageTitle输出keywords和description,自定义组件

    在blazor的PageTitle中不具备输出keywords和description的功能,而如果直接使用<mate>标签,输出中文时会变成乱码,所以我给大家推介下面的代码解君愁: 1 ...

  7. 一键自动化博客发布工具,用过的人都说好(oschina篇)

    oschina和segmentfault一样,界面非常的清爽. 界面上除了必须的标题,内容之外,还有文章专辑和推广专区这几个选项. 一起来看看在blog-auto-publishing-tools中, ...

  8. gin 图片上传到本地或者oss

    路由层 func registerCommonRouter(v1 *gin.RouterGroup) { up := v1.Group("upload") { up.POST(&q ...

  9. UE4 绘制Gizmo

    Unity的Gizmos可以很方便的在编辑器下进行调试,Unreal中也有一些办法可以达到效果. 本文主要参考:https://zhuanlan.zhihu.com/p/363625037,进行了一些 ...

  10. ETSI GS MEC 015,MEP 带宽管理 API

    目录 文章目录 目录 版本 ETSI MEC 对 MEP 带宽管理功能的定义 功能理解 Bandwidth Management Service BWMS UML ME APP registers t ...