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” ...
随机推荐
- 期货大赛项目|九,fileinput插件的应用
引入JS和CSS bundles.Add(new ScriptBundle("~/bundles/fileinputJs").Include( "~/Content/ve ...
- 斐波那契求第n项
摘自 https://blog.csdn.net/lpjishu/article/details/51323116 斐波那契求第n项是常见的算法题 方法1 递归法 //斐波那契 0,1,1,2,3 ...
- ABP给WebApi添加性能分析组件Miniprofiler
在ABP的WebApi中,对其性能进行分析监测是很有必要的.而悲剧的是,MVC项目中可以使用的MiniProfiler或Glimpse等,这些都不支持WebApi项目,而且WebApi项目通常也没有界 ...
- python 的 virtualenv 环境搭建及 sublime 手动创建运行环境
一.安装 virtual env sudo pip install virtualenv二.进入一个空白的目录初始化 virtual env 的环境cd ~/workspace/python/virt ...
- port bridge enable命令导致的环路
1.故障描述 前几天机房一台连接数据中心与核心交换的交换机宕机(硬件故障),机房有备用的设备,随即更换(配置也是早就配置好了的),但是下午就出现数据中心网络丢包问题,表现为存在mac漂移 2.拓扑 核 ...
- [CF566A]Matching Names
[CF566A]Matching Names 题目大意: A组和B组各\(n(n\le10^5)\)个字符串\((\sum|S|\le8\times10^5)\),将它们两两匹配,使得每组两个字符串的 ...
- XIII Open Grodno SU Championship
A. Alice in the Wonderland 按题意模拟. #include<stdio.h> #include<iostream> #include<strin ...
- css Margin-top塌陷,解决方法
在两个盒子嵌套时,内部的盒子设置的margin-top会加到外边的盒子上,导致内部的盒子margin-top设置失败,解决方法如下: (1)外部盒子设置一个边框 (2)外部盒子设置overflow:h ...
- Linux bash基础特性一
命令别名 alias cdnet=”cd /etc/sysconfig/network-scripts” 针对用户的别名: “~/.bashrc” 针对系统的别名:”/etc/bashrc” 重读配置 ...
- Oracle 11g修改字符集
选择静默安装的安装字符集为默认的ZHS16GBK,工作中字符集为为AL32UTF8 一.登录oracle sqlplus / as sysdba shutdown immediate; STARTUP ...