TCP 数据传输工具类
package com.ivchat.test.propertysystem.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import javax.imageio.stream.FileImageInputStream;
public class HttpRequstTestUtil {
public static String send(String reqUrl, String jsonData) {
System.out.println("请求数据:"+reqUrl);
System.out.println(jsonData);
// jsonData = URLEncoder.encode(jsonData, "utf-8");
HttpURLConnection urlConn = null;
OutputStream out = null;
InputStreamReader in = null;
BufferedReader bufferedReader = null;
String result = "";
try {
URL url = new URL(reqUrl);
// 打开一个HttpURLConnection连接
urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(5 * 1000);
// Post请求必须设置允许输出
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
// Post请求不能使用缓存
urlConn.setUseCaches(false);
// 设置为Post请求
urlConn.setRequestMethod("POST");
urlConn.setInstanceFollowRedirects(true);
urlConn.setRequestProperty("Accept-Charset", "UTF-8");
urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
// 开始连接
urlConn.connect();
// 发送请求参数
if (jsonData != null) {
out = urlConn.getOutputStream();
out.write(jsonData.getBytes("UTF-8"));
out.flush();
}
// 判断请求是否成功
in = new InputStreamReader(urlConn.getInputStream());
bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
result = strBuffer.toString();
System.out.println("-----返回结果-----");
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (urlConn != null) {
urlConn.disconnect();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
public static String sendToMall(String reqUrl, String jsonData) {
System.out.println("请求数据:");
System.out.println(jsonData);
// jsonData = URLEncoder.encode(jsonData, "utf-8");
HttpURLConnection urlConn = null;
OutputStream out = null;
InputStreamReader in = null;
BufferedReader bufferedReader = null;
String result = "";
try {
URL url = new URL(reqUrl);
// 打开一个HttpURLConnection连接
urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(5 * 1000);
// Post请求必须设置允许输出
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
// Post请求不能使用缓存
urlConn.setUseCaches(false);
// 设置为Post请求
urlConn.setRequestMethod("POST");
urlConn.setInstanceFollowRedirects(true);
urlConn.setRequestProperty("Accept-Charset", "UTF-8");
urlConn.setRequestProperty("Content-Encoding", "UTF-8");
urlConn.setRequestProperty("Content-Type","application/x-www.form-urlencoded");
// 开始连接
urlConn.connect();
// 发送请求参数
if (jsonData != null) {
out = urlConn.getOutputStream();
out.write(jsonData.getBytes("UTF-8"));
out.flush();
}
// 判断请求是否成功
in = new InputStreamReader(urlConn.getInputStream());
bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
result = strBuffer.toString();
System.out.println("-----返回结果-----");
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (urlConn != null) {
urlConn.disconnect();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
public static String upFile(String reqUrl, String name, Map<String,String> map) {
if(map.size() > 0){
String end = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------823928434";
try {
URL url = new URL(reqUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setInstanceFollowRedirects(true);
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
for (Map.Entry<String, String> entry : map.entrySet()) {
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; name="+name+"; filename="+entry.getKey() + end);
dos.writeBytes(end);
dos.write(image2byte(entry.getValue()));
dos.writeBytes(end);
}
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
// 读取服务器返回结果
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();
System.out.println(result);
is.close();
return result;
} catch (Exception e) {
e.printStackTrace();
}
}
return "";
}
public static void upload(String reqUrl, File file) throws Exception {
System.out.println("请求数据:");
HttpURLConnection urlConn = null;
OutputStream out = null;
DataInputStream in = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL(reqUrl);
// 打开一个HttpURLConnection连接
urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(5 * 1000);
// Post请求必须设置允许输出
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
// Post请求不能使用缓存
urlConn.setUseCaches(false);
// 设置为Post请求
urlConn.setRequestMethod("POST");
urlConn.setInstanceFollowRedirects(true);
urlConn.setRequestProperty("Accept-Charset", "UTF-8");
urlConn.setRequestProperty("contentType", "UTF-8");
// 开始连接
urlConn.connect();
// 发送请求参数
urlConn.setRequestProperty("Content-Type","multipart/form-data");
urlConn.setRequestProperty("filename", file.getName());
out = new DataOutputStream(urlConn.getOutputStream());
in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (urlConn != null) {
urlConn.disconnect();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public static byte[] image2byte(String path){
byte[] data = null;
FileImageInputStream input = null;
try {
input = new FileImageInputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
}
catch (FileNotFoundException ex1) {
ex1.printStackTrace();
}
catch (IOException ex1) {
ex1.printStackTrace();
}
return data;
}
}
TCP 数据传输工具类的更多相关文章
- TCP 服务端接收数据解析工具类
package com.ivchat.common.util; import java.io.BufferedReader;import java.io.IOException;import java ...
- [转]Java常用工具类集合
转自:http://blog.csdn.net/justdb/article/details/8653166 数据库连接工具类——仅仅获得连接对象 ConnDB.java package com.ut ...
- Mina工具类v1.5
package com.cucpay.fundswap.util; import java.net.InetSocketAddress; import java.nio.charset.Charset ...
- Android开源项目发现--- 工具类网络相关篇(持续更新)
1. Asynchronous Http Client for Android Android异步Http请求 项目地址:https://github.com/loopj/android-async- ...
- Android开源项目大全 - 工具类
主要包括那些不错的开发库,包括依赖注入框架.图片缓存.网络相关.数据库ORM建模.Android公共库.Android 高版本向低版本兼容.多媒体相关及其他. 一.依赖注入DI 通过依赖注入减少Vie ...
- 项目经验分享——Java常用工具类集合 转
http://blog.csdn.net/xyw591238/article/details/51678525 写在前面 本文涉及的工具类部分是自己编写,另一部分是在项目里收集的.工具类涉及数 ...
- Socket网络编程(TCP/IP/端口/类)和实例
Socket网络编程(TCP/IP/端口/类)和实例 原文:C# Socket网络编程精华篇 转自:微冷的雨 我们在讲解Socket编程前,先看几个和Socket编程紧密相关的概念: TCP/IP层次 ...
- Netty源码分析第8章(高性能工具类FastThreadLocal和Recycler)---->第7节: 获取异线程释放的对象
Netty源码分析第八章: 高性能工具类FastThreadLocal和Recycler 第七节: 获取异线程释放的对象 上一小节分析了异线程回收对象, 原理是通过与stack关联的WeakOrder ...
- linux rsync-文件同步和数据传输工具
一.rsync的概述 rsync是类unix系统下的数据镜像备份工具,从软件的命名上就可以看出来了——remote sync.rsync是Linux系统下的文件同步和数据传输工具,它采用“rsync” ...
随机推荐
- Codeforces 750E New Year and Old Subsequence 线段树 + dp (看题解)
New Year and Old Subsequence 第一感觉是离线之后分治求dp, 但是感觉如果要把左边的dp值和右边的dp值合起来, 感觉很麻烦而且时间复杂度不怎么对.. 然后就gun取看题解 ...
- Linux awk学习
零.awk标准语法 [root@wohaoshuai1 bbb]# echo "abcd" |awk 'BEGIN{print "wohaoshuai"} /a ...
- UOJ#460. 新年的拯救计划 构造
原文链接https://www.cnblogs.com/zhouzhendong/p/UOJ460.html 题解 本题的构造方法很多.这里只介绍一种. 首先,总边数为 $\frac{n(n-1)}2 ...
- ruby配合gem使用sass
Ruby环境安装 1.Ruby安装包下载地址:http://rubyinstaller.org/downloads/下载对应系统版本的安装包: 2.双击rubyinstaller-2.2.3-x64. ...
- 在Node.js中使用ffi调用dll
类似的文章还是比较多的,但或多或少有一些问题没有解决,在此我将其整合并分享给大家: 测试环境: Node.js 9.9.0 VisualStudio 2015 "ffi": &qu ...
- 69. x 的平方根
问题描述 实现 int sqrt(int x) 函数. 计算并返回 x 的平方根,其中 x 是非负整数. 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去. 示例 1: 输入: 4 输出: ...
- python学习:常量和变量
变量的作用:存储信息,日后被调用和修改操作. 常量:固定不变得量,字母要大些. 变量的命名规则: 1.由字母数字下划线组成: 2.不能以数字开头,不能含有特殊字符和空格: 3.不能以保留字命名: 4. ...
- (98)Wangdao.com_第三十天_拖拉事件
拖拉事件 拖拉 drag ,是指用户在某个对象上按下鼠标键不放,拖动它到另一个位置,然后释放鼠标键,将该对象放在那里. 一旦某个元素节点的 draggable 属性设为true,就无法再用鼠标选中该节 ...
- PHP的运算符
1.算术运算符 2.赋值运算符 基本的赋值运算符是“=”. (1)引用赋值 PHP 支持引用赋值,使用“$var = &$othervar;”语法.引用赋值意味着两个变量指向了同一个数据,没有 ...
- F#周报2019年第9期
新闻 对于F#,Visual Studio 2019 RC有哪些更新 Visual Studio 2019 RC现在已经发布 C#版本与工具的升级 如何移植桌面应用程序到.NET Core 3.0 对 ...