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. Anroid ActionBar 学习资源

    Android ActionBar完全解析,使用官方推荐的最佳导航栏(上) http://blog.csdn.net/yuzhiboyi/article/details/32709833 Androi ...

  2. C#winform自定义滚动条

    1.控件 一个UserControl作为ScrollBg,一个panel作为ScrollBar 2.实现功能 (1)设置滚动条背景颜色和背景图片 (2)设置滚动条滑块的背景颜色和背景图片 (3)鼠标左 ...

  3. Conditional Expressions

    Conditional Expressions建立一些逻辑关系 The conditional expression classes from django.db import models clas ...

  4. 8 个用于生产环境的 SQL 查询优化调整

    在没有数据仓库或单独的分析数据库的组织中,报告的唯一来源和最新的数据可能是在现场生产数据库中. 在查询生产数据库时,优化是关键.一个低效的查询可能会对生产数据库产生大量的资源消耗,如果查询有错误会引发 ...

  5. IO模型《五》异步IO

    Linux下的asynchronous IO其实用得不多,从内核2.6版本才开始引入.先看一下它的流程: 用户进程发起read操作之后,立刻就可以开始去做其它的事.而另一方面,从kernel的角度,当 ...

  6. for循环 | range 对象

    # ### for循环 # 循环 遍历 迭代 # 把列表的元素一一的拿出来遍历 listvar = ["黄雄大","黄文","黄仪正",&q ...

  7. linux 安全配置随笔

    1. 禁止Ctrl+Alt+Del直接重启服务器 /bin/mv /etc/init/control-alt-delete.conf /etc/init/control-alt-delete.conf ...

  8. java集合类学习笔记之LinkedHashMap

    1.简述 LinkedHashMap是HashMap的子类,他们最大的不同是,HashMap内部维护的是一个单向的链表数组,而LinkedHashMap内部维护的是一个双向的链表数组.HashMap是 ...

  9. 集成 jpush-react-native 常见问题汇总 (iOS 篇)

    给 iOS 应用添加推送功能是一件比较麻烦的事情,本篇文章收集了集成 jpush-react-native 的常见问题,目的是为了帮助用户更好地排查问题 1. 收不到推送 确保是在真机上测试,而不是在 ...

  10. Azure自定义角色实现RBAC

    简要说明: 当前Azure Portal上只能针对订阅或具体某一资源,实现访问控制,也就是对某一具体资源实现访问/使用/删除,但无法实现创建.例如:当前的需求为,新添加用户只具有对CDN服务的管理使用 ...