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 = " ";
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;
}

}

原文地址:https://www.cnblogs.com/yy00/p/9000935.html