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 数据传输工具类的更多相关文章

  1. TCP 服务端接收数据解析工具类

    package com.ivchat.common.util; import java.io.BufferedReader;import java.io.IOException;import java ...

  2. [转]Java常用工具类集合

    转自:http://blog.csdn.net/justdb/article/details/8653166 数据库连接工具类——仅仅获得连接对象 ConnDB.java package com.ut ...

  3. Mina工具类v1.5

    package com.cucpay.fundswap.util; import java.net.InetSocketAddress; import java.nio.charset.Charset ...

  4. Android开源项目发现--- 工具类网络相关篇(持续更新)

    1. Asynchronous Http Client for Android Android异步Http请求 项目地址:https://github.com/loopj/android-async- ...

  5. Android开源项目大全 - 工具类

    主要包括那些不错的开发库,包括依赖注入框架.图片缓存.网络相关.数据库ORM建模.Android公共库.Android 高版本向低版本兼容.多媒体相关及其他. 一.依赖注入DI 通过依赖注入减少Vie ...

  6. 项目经验分享——Java常用工具类集合 转

    http://blog.csdn.net/xyw591238/article/details/51678525 写在前面     本文涉及的工具类部分是自己编写,另一部分是在项目里收集的.工具类涉及数 ...

  7. Socket网络编程(TCP/IP/端口/类)和实例

    Socket网络编程(TCP/IP/端口/类)和实例 原文:C# Socket网络编程精华篇 转自:微冷的雨 我们在讲解Socket编程前,先看几个和Socket编程紧密相关的概念: TCP/IP层次 ...

  8. Netty源码分析第8章(高性能工具类FastThreadLocal和Recycler)---->第7节: 获取异线程释放的对象

    Netty源码分析第八章: 高性能工具类FastThreadLocal和Recycler 第七节: 获取异线程释放的对象 上一小节分析了异线程回收对象, 原理是通过与stack关联的WeakOrder ...

  9. linux rsync-文件同步和数据传输工具

    一.rsync的概述 rsync是类unix系统下的数据镜像备份工具,从软件的命名上就可以看出来了——remote sync.rsync是Linux系统下的文件同步和数据传输工具,它采用“rsync” ...

随机推荐

  1. Django REST framework serializer 嵌套显示绝对路径

    在 Django REST framework官方文档提到,当调用Serializer时,应当传入request参数,以便生成完整的url而不是相对url.使用ModelSerializer时requ ...

  2. Kafka生产者发送消息的三种方式

    Kafka是一种分布式的基于发布/订阅的消息系统,它的高吞吐量.灵活的offset是其它消息系统所没有的. Kafka发送消息主要有三种方式: 1.发送并忘记 2.同步发送 3.异步发送+回调函数 下 ...

  3. 识别拖动与点击操作之zepto的bug

    问题描述:给页面<a>标签绑定了tap事件,在移动设备上点击按钮貌似一切正常,可以响应.但是,把页面上下滑动几次之后,或者在滑动时手指滑动出移动屏幕之外,之后再点击按钮,就会发现第一次点击 ...

  4. 什么是 B 树?

    本文提到的「B-树」,就是「B树」,都是 B-tree 的翻译,里面不是减号-,是连接符-.因为有人把 B-tree 翻成 「B-树」,让人以为「B树」和「B-树」是两种树,实际上两者就是同一种树. ...

  5. selenium基础实例学习

    在这里我们通过selenium官方文档做给的实例以及翻译,做出如果代码注释   from selenium import webdriverfrom selenium.webdriver.common ...

  6. Sting、StringBuffer、StringBuilder

    (1)String是字符串常量,一旦创建之后不可更改:StringBuffer和StringBuilder是字符串变量,可以更改.String的不可变,所以适合作为Map的键. (2)StringBu ...

  7. Buffer --缓冲器

    一. 启动Buffer缓冲器 node 输入 buffer 创建一个新的buffer var buf = new buffer(''hello word) 查看buf的长度 buf.length 运行 ...

  8. 解析CommandMessage

    Json 解析: void CommandMessage::ParseCmdBody() { try { Json::Reader reader; Json::Value root; if (!rea ...

  9. Android 基础知识

    system/app   与   system/priv-app Android4.4系统在system目录下新增了priv-app目录,在该目录下的apk一般都是系统核心应用如Launcher.sy ...

  10. 使用DevExpress.XtraTabbedMdi.XtraTabbedMdiManager控件来加载MDI窗体

    使用DevExpress.XtraTabbedMdi.XtraTabbedMdiManager控件来加载MDI窗体     [csharp] view plaincopyprint? <SPAN ...