java服务器访问其他服务器工具类编写
java服务器访问其他服务器工具类编写
适合各种消息推送及微服务交互
package com.xiruo.medbid.components; import com.xiruo.medbid.util.UtilConstants;
import net.sf.json.JSONObject; import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map; public class HttpRequestUtils { // default time out setting , half minute
private static final int defaultTimeOut = * ; private static void validateUrl(String url) {
if (!URLUtils.isUseHttpProtocol(url)) {
throw new java.lang.IllegalArgumentException(String.format(
"The URL %s is illegal", url));
}
} public static String doGet(String url, String charSetName, int timeOut)
throws Exception {
validateUrl(url);
try {
URL ur = new URL(url);
URLConnection con = ur.openConnection();
con.setConnectTimeout(timeOut);
con.setReadTimeout(timeOut);
BufferedReader rd = new BufferedReader(new InputStreamReader(con
.getInputStream(), charSetName));
StringBuilder sb = new StringBuilder();
try {
int k = rd.read();
while (k != -) {
sb.append((char) k);
k = rd.read();
}
} catch (Exception ee) {
} finally {
if (rd != null) {
rd.close();
}
}
return sb.toString();
} catch (Exception e) {
throw new Exception(e);
}
} public static String doGet(String url, String charSetName) throws Exception {
return doGet(url, charSetName, defaultTimeOut);
} public static String doGet(String url) throws Exception {
return doGet(url, UtilConstants.DEFAULT_CHARSET, defaultTimeOut);
} public static void doGetFile(String url, int timeOut, String fullFileName)
throws Exception {
validateUrl(url);
InputStream is = null;
OutputStream os = null;
try {
URL ur = new URL(url);
URLConnection con = ur.openConnection();
con.setConnectTimeout(timeOut);
con.setReadTimeout(timeOut); is = con.getInputStream(); // 1K cache
byte[] bs = new byte[];
// length
int len; os = new FileOutputStream(fullFileName);
while ((len = is.read(bs)) != -) {
os.write(bs, , len);
}
} catch (Exception e) {
throw new Exception(e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
} public static InputStream doGetStream(String url, int timeOut)
throws Exception {
validateUrl(url);
InputStream is = null;
try {
URL ur = new URL(url);
URLConnection con = ur.openConnection();
con.setConnectTimeout(timeOut);
con.setReadTimeout(timeOut);
is = con.getInputStream();
return is;
} catch (Exception e) {
throw new Exception(e);
} finally {
if (is != null) {
try {
is.close();
} catch (Exception unusede) {
}
}
}
} public static String doPost(String url, Map<String, String> parameters,
int timeOut, String charSetName) throws Exception {
// validate
validateUrl(url); // generate post data form parameters
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> kv : parameters.entrySet()) {
sb.append(kv.getKey());
sb.append("=");
sb.append(URLUtils.decode(kv.getValue()));
sb.append("&");
}
if (sb.length() > ) {
sb.deleteCharAt(sb.length() - );
}
byte[] postData = BytesUtils.toBytes(sb);
try {
URL ur = new URL(url);
URLConnection con = ur.openConnection(); // setting
con.setConnectTimeout(timeOut);
con.setReadTimeout(timeOut);
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setDefaultUseCaches(false); con.setRequestProperty("Content-Length", postData.length + "");
OutputStream os = con.getOutputStream(); os.write(postData);
os.flush();
os.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(con
.getInputStream(), charSetName));
StringBuilder rsb = new StringBuilder();
try {
int k = rd.read();
while (k != -) {
rsb.append((char) k);
k = rd.read();
}
} catch (Exception ee) {
} finally {
try {
rd.close();
} catch (Exception e) { }
}
return rsb.toString();
} catch (Exception e) {
throw new Exception(e);
}
} public static String doPost(String url, Map<String, String> parameters,
int timeOut) throws Exception {
return HttpRequestUtils
.doPost(url, parameters, timeOut, UtilConstants.DEFAULT_CHARSET);
} public static String doPost(String url, Map<String, String> parameters)
throws Exception {
return HttpRequestUtils.doPost(url, parameters, defaultTimeOut,
UtilConstants.DEFAULT_CHARSET);
} public static int doHead(String url, int timeOut) throws Exception {
validateUrl(url);
try {
URL ur = new URL(url);
HttpURLConnection con = (HttpURLConnection) ur.openConnection();
con.setConnectTimeout(timeOut);
return con.getResponseCode();
} catch (Exception e) {
throw new Exception(e);
}
} public static int doHead(String url) throws Exception {
return doHead(url, defaultTimeOut);
} public static JSONObject doPostByJson(String httpUrl, JSONObject jsonObject) throws IOException {
return doPostByJson(httpUrl, jsonObject, );
} public static JSONObject doPostByJson(String httpUrl, JSONObject jsonObject, Integer timeout) throws IOException {
StringBuffer sb = null;
HttpURLConnection connection=null;
OutputStreamWriter out=null;
BufferedReader reader=null;
JSONObject returnObj=null;
try {
//创建连接
URL url = new URL(httpUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
if (null != timeout) {
connection.setReadTimeout( * );
} else {
connection.setReadTimeout(timeout);
}
// connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Type", "application/json; charset=utf8");
connection.connect(); //POST请求
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
System.out.println("请求参数:"+jsonObject.toString());
out.write(jsonObject.toString());
out.flush(); //读取响应
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String lines;
sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
sb.append(lines);
}
System.out.println("响应参数:"+sb);
if(sb.length()>){
returnObj= JSONObject.fromObject(sb.toString().replaceAll("\n","").replaceAll("null","\"null\""));
}
// 断开连接
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(out!=null){
out.flush();
out.close();
}
if(reader!=null){
reader.close();
}
if(connection!=null){
connection.disconnect();
}
}
return returnObj;
} }
调用
JSONObject response = HttpRequestUtils.doPostByJson(url, json);
java服务器访问其他服务器工具类编写的更多相关文章
- 一、JDBC的概述 二、通过JDBC实现对数据的CRUD操作 三、封装JDBC访问数据的工具类 四、通过JDBC实现登陆和注册 五、防止SQL注入
一.JDBC的概述###<1>概念 JDBC:java database connection ,java数据库连接技术 是java内部提供的一套操作数据库的接口(面向接口编程),实现对数 ...
- java后台表单验证工具类
/** * 描述 java后台表单验证工具类 * * @ClassName ValidationUtil * @Author wzf * @DATE 2018/10/27 15:21 * @VerSi ...
- 【转】Java压缩和解压文件工具类ZipUtil
特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...
- Java操作文件夹的工具类
Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...
- Java汉字转成汉语拼音工具类
Java汉字转成汉语拼音工具类,需要用到pinyin4j.jar包. import net.sourceforge.pinyin4j.PinyinHelper; import net.sourcefo ...
- java中excel导入\导出工具类
1.导入工具 package com.linrain.jcs.test; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import ...
- java中定义一个CloneUtil 工具类
其实所有的java对象都可以具备克隆能力,只是因为在基础类Object中被设定成了一个保留方法(protected),要想真正拥有克隆的能力, 就需要实现Cloneable接口,重写clone方法.通 ...
- java代码行数统计工具类
package com.syl.demo.test; import java.io.*; /** * java代码行数统计工具类 * Created by 孙义朗 on 2017/11/17 0017 ...
- [转]SQLSERVER存储过程调用不同数据库的数据_存储过程中通过链接服务器访问远程服务器
本文转自:http://blog.csdn.net/nnaabbcc/article/details/7967761 存储过程调用不同数据库的数据 在存储过程调用不同数据库的数据该如何做,比如在存储过 ...
随机推荐
- 在eclipse上的hdfs的文件操作
参考:http://dblab.xmu.edu.cn/blog/hadoop-build-project-using-eclipse/?tdsourcetag=s_pcqq_aiomsg: http ...
- read_csv 函数
转载自 https://www.cnblogs.com/datablog/p/6127000.html pandas.read_csv参数整理 读取CSV(逗号分割)文件到DataFrame也支持文件 ...
- linux 安装python3.7 报错No module named '_ctypes'
ModuleNotFoundError: No module named '_ctypes' 操作系统:centos yum install libffi-devel ./configure --en ...
- 2018OCP最新题库052新加考题及答案整理-27
27.Examine these facts about a database: 1. USERS is the database default tablespace. 2. USER1, USER ...
- sonar阻断级别错误(block)简单汇总
1.代码里面包含PASSWORD.PWD 'PWD' detected in this expression, review this potentially hardcoded credential ...
- 洛谷P3783 [SDOI2017]天才黑客(前后缀优化建图+虚树+最短路)
题面 传送门 题解 去看\(shadowice\)巨巨写得前后缀优化建图吧 话说我似乎连线段树优化建图的做法都不会 //minamoto #include<bits/stdc++.h> # ...
- 快速启动工具Rulers 4.1
Rulers 4.1 Release 360云盘 https://yunpan.cn/cSbq5nx9GVwrJ 访问密码 0532 百度云 http://pan.baidu.com/s/1czCNR ...
- dataTable 从服务器获取数据源的两种表现形式
var table = $('#example1').DataTable({ "processing": true,//加载效果 "autoWidth": fa ...
- struts中如何查看配置文件中是否存在某个返回值
ActionConfig config = ActionContext.getContext() .getActionInvocation().getProxy().getConfig(); Resu ...
- 循环神经网络RNN原理
一.循环神经网络简介 循环神经网络,英文全称:Recurrent Neural Network,或简单记为RNN.需要注意的是,递归神经网络(Recursive Neural Network)的简写也 ...