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服务器访问其他服务器工具类编写的更多相关文章

  1. 一、JDBC的概述 二、通过JDBC实现对数据的CRUD操作 三、封装JDBC访问数据的工具类 四、通过JDBC实现登陆和注册 五、防止SQL注入

    一.JDBC的概述###<1>概念 JDBC:java database connection ,java数据库连接技术 是java内部提供的一套操作数据库的接口(面向接口编程),实现对数 ...

  2. java后台表单验证工具类

    /** * 描述 java后台表单验证工具类 * * @ClassName ValidationUtil * @Author wzf * @DATE 2018/10/27 15:21 * @VerSi ...

  3. 【转】Java压缩和解压文件工具类ZipUtil

    特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...

  4. Java操作文件夹的工具类

    Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...

  5. Java汉字转成汉语拼音工具类

    Java汉字转成汉语拼音工具类,需要用到pinyin4j.jar包. import net.sourceforge.pinyin4j.PinyinHelper; import net.sourcefo ...

  6. java中excel导入\导出工具类

    1.导入工具 package com.linrain.jcs.test; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import ...

  7. java中定义一个CloneUtil 工具类

    其实所有的java对象都可以具备克隆能力,只是因为在基础类Object中被设定成了一个保留方法(protected),要想真正拥有克隆的能力, 就需要实现Cloneable接口,重写clone方法.通 ...

  8. java代码行数统计工具类

    package com.syl.demo.test; import java.io.*; /** * java代码行数统计工具类 * Created by 孙义朗 on 2017/11/17 0017 ...

  9. [转]SQLSERVER存储过程调用不同数据库的数据_存储过程中通过链接服务器访问远程服务器

    本文转自:http://blog.csdn.net/nnaabbcc/article/details/7967761 存储过程调用不同数据库的数据 在存储过程调用不同数据库的数据该如何做,比如在存储过 ...

随机推荐

  1. Django Query

    Making Qeries 一旦创建了数据模型,Django就会自动为您提供一个数据库抽象API,允许您创建.检索.更新和删除对象.本文档解释了如何使用这个API. The models 一个clas ...

  2. windbg 常用命令详解

    = kd> ln 8046e100 (8046e100) nt!KeServiceDescriptorTableShadow | (8046e140) nt!MmSectionExtendRes ...

  3. leecode刷题(10)-- 旋转图像

    leecode刷题(10)-- 旋转图像 旋转图像 描述: 给定一个 n × n 的二维矩阵表示一个图像. 将图像顺时针旋转 90 度. 说明: 你必须在原地旋转图像,这意味着你需要直接修改输入的二维 ...

  4. 如何提高scrapy的爬取效率

    提高scrapy的爬取效率 增加并发: 默认scrapy开启的并发线程为32个,可以适当进行增加.在settings配置文件中修改CONCURRENT_REQUESTS = 100值为100,并发设置 ...

  5. Windows下磁盘无损重新分配

    打开百度(www.baidu.com),找到我们的分区助手.exe 单击“普通下载”,会下载一个安装包. 这时候,我们进行安装.安装完成如下. 对着那个盘容量较大的盘右键,分配空闲空间. 服务器多次重 ...

  6. P1117 [NOI2016]优秀的拆分

    $ \color{#0066ff}{ 题目描述 }$ 如果一个字符串可以被拆分为\(AABB\)的形式,其中 A和 B是任意非空字符串,则我们称该字符串的这种拆分是优秀的. 例如,对于字符串\(aab ...

  7. webpack---less+热更新 使用

    最近尝试用less写界面,webpack进行打包,然后发现每次修改less时都需要重新执行webpack打包一下,于是就想到了webpack热更新这个功能. 一.使用less less是一门css预处 ...

  8. 963 AlvinZH打怪刷经验(背包DP大作战R)

    963 AlvinZH打怪刷经验 思路 这不是一道普通的01背包题.大家仔细观察数据的范围,可以发现如果按常理来的话,背包容量特别大,你也会TLE. 方法一:考虑01背包的一个常数优化----作用甚微 ...

  9. docker 安装sentry

    主页:https://sentry.io/welcome/ 环境安装 请先安装 Docker 1.10+ ,使用 CE 版本:安装文档,写的很清晰,不详述:因为国内网络环境问题,一般建议 docker ...

  10. train loss与test loss结果分析

    train loss 不断下降,test loss不断下降,说明网络仍在学习; train loss 不断下降,test loss趋于不变,说明网络过拟合; train loss 趋于不变,test ...