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. EF修改model自动更新数据库

    最近用MVC+EF学习时遇到修改model后而数据库没更新报错,就在网上找关于数据迁移自动更新数据库的,折腾了大半天终于弄了出来 第一步:在程序包管理器控制台里: Enable-Migrations ...

  2. WinForm中Button的使用

    自定义样式 先要清除系统风格影响:this.FlatStyle = FlatStyle.Flat; FlatStyle.Flat FlatStyle.System FlatStyle.Standard ...

  3. leetcode 2 两数相加 JAVA

    题目: 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两个数相加起来,则会返回一个新的链表来表示 ...

  4. 如何获得Android设备名称(ADB命令详细介绍)

    豌豆荚.360手机管家等软件可以获取android设备名称,显示在界面上,如下图: 我们自己如何来获取设备名称 呢?答案如下: 在命令行中输入“adb shell”进入shell之后,再输入“cat ...

  5. [Flex] 动态获取组件宽度和高度

    flex中我们有时并不想一开始就设置某个组件的宽度和高度,而想动态获取某个组件经填充后的width和height,但是会发现width和height均为0,这时我们可以注册一下两个事件之一来解决. i ...

  6. [转] 配置文件现在需要绝密的短语密码(blowfish_secret)的解决方法

    今天在使用 phpMyAdmin 操作数据库时,刚刚登陆后发现最下面有如下信息提示: 配置文件现在需要绝密的短语密码(blowfish_secret). 园子在网上找了多种解决方法,写的都不是非常详细 ...

  7. Linux CentOs 下 安装 mysql nginx redis

    SCP 的使用 来源于: https://blog.csdn.net/qq_30968657/article/details/72912070 scp [参数] <源地址(用户名@IP地址或主机 ...

  8. 接口自动化之unittest初探

    最近几天苦心钻研unittest,终于略有所得,所以想来跟大家分享一下.有关python和unittest的基础知识部分就不在一一细说,相信各位也不是小白了.如果需要我整理基础知识,欢迎留言,我会看情 ...

  9. [转] linux nc命令

    [From] https://blog.csdn.net/freeking101/article/details/53289198 NC 全名 Netcat (网络刀),作者是 Hobbit & ...

  10. ABP相关网站

    ABP的官方网站:http://www.aspnetboilerplate.com ABP在Github上的开源项目:https://github.com/aspnetboilerplate 系列文章 ...