package com.wondersoft.dlp.web.apt.util;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.omg.CORBA.UserException;
import net.sf.jmimemagic.Magic;
import net.sf.jmimemagic.MagicMatch;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
public class UtillHttpClient {
private final static String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符;
/**
* 测试接口GET
*/
public static void paramGet(){
String url ="";
String param="taskIds=11";
String result=sendGet(url, param);
JSON json=JSONObject.fromObject(result);
System.out.println("json个数:"+json.size());
System.out.println(result);
}
/**
* 测试接口POST
*/
public static String paramPost(){
String url ="";
List<String>list=new ArrayList<String>();
list.add("11");
list.add("12");
list.add("13");
list.add("14");
list.add("15");
String result="";
try {
result= sendPost(url, list);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
* 发送任务ID 返回当前任务状态信息
* @param url
* 发送请求的 URL
* @param param
*
* @return 所代表远程资源的响应结果
* @throws IOException
*/
public static String sendPost(String urlStr, List taskIds) throws IOException {
String res = "";
HttpURLConnection conn = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 添加参数
StringBuffer strBuf = new StringBuffer();
for(int i=0;i<taskIds.size();i++){
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + "taskIds" + "\"\r\n\r\n");
strBuf.append(taskIds.get(i));
}
System.out.println(strBuf);
out.write(strBuf.toString().getBytes());
byte[]endDate = ("\r\n--"+BOUNDARY+"--\r\n").getBytes();
out.write(endDate);
out.flush();
out.close();
// 读取返回数据
StringBuffer str = new StringBuffer("");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line).append("\n");
}
res = str.toString();
reader.close();
reader = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
/**
* 向指定URL发送GET方法的请求
* 发送任务ID,返回任务详情
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
/*// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}*/
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 防止乱码
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 读写文件
*/
public static void rwFile(String outPath,String intPath){
FileWriter fw = null;
BufferedReader br = null;
try {
fw = new FileWriter(outPath, true);
br = new BufferedReader(new InputStreamReader(
new FileInputStream(intPath), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("文件内容: " + line);
fw.write(line);
fw.flush();
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 上传文件
* @param urlStr
* @param params 参数集合
* @param filePath 样本路径
* @return
* @throws UserException
*/
public static String formUpload(String urlStr, Map<String, String> textMap, String filePath) throws UserException {
String res = "";
HttpURLConnection conn = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
//conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 添加参数
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
System.out.println("strBuf.toString():"+strBuf.toString());
out.write(strBuf.toString().getBytes());
}
// file
File file = new File(filePath);
String filename = file.getName();
//获取文件类型
String contentType="text/plain";//默认类型
try {
MagicMatch match = Magic.getMagicMatch(file, false, true);
contentType = match.getMimeType();
} catch (Exception e) {
}
StringBuffer fileStrBuf = new StringBuffer();
fileStrBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
fileStrBuf.append("Content-Disposition: form-data; name=\"sampleFile\"; filename=\"" + filename + "\"\r\n");
fileStrBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(fileStrBuf.toString().getBytes());
DataInputStream 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);
}
in.close();
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
}
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.omg.CORBA.UserException;
import net.sf.jmimemagic.Magic;
import net.sf.jmimemagic.MagicMatch;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
public class UtillHttpClient {
private final static String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符;
/**
* 测试接口GET
*/
public static void paramGet(){
String url ="";
String param="taskIds=11";
String result=sendGet(url, param);
JSON json=JSONObject.fromObject(result);
System.out.println("json个数:"+json.size());
System.out.println(result);
}
/**
* 测试接口POST
*/
public static String paramPost(){
String url ="";
List<String>list=new ArrayList<String>();
list.add("11");
list.add("12");
list.add("13");
list.add("14");
list.add("15");
String result="";
try {
result= sendPost(url, list);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
* 发送任务ID 返回当前任务状态信息
* @param url
* 发送请求的 URL
* @param param
*
* @return 所代表远程资源的响应结果
* @throws IOException
*/
public static String sendPost(String urlStr, List taskIds) throws IOException {
String res = "";
HttpURLConnection conn = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 添加参数
StringBuffer strBuf = new StringBuffer();
for(int i=0;i<taskIds.size();i++){
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + "taskIds" + "\"\r\n\r\n");
strBuf.append(taskIds.get(i));
}
System.out.println(strBuf);
out.write(strBuf.toString().getBytes());
byte[]endDate = ("\r\n--"+BOUNDARY+"--\r\n").getBytes();
out.write(endDate);
out.flush();
out.close();
// 读取返回数据
StringBuffer str = new StringBuffer("");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line).append("\n");
}
res = str.toString();
reader.close();
reader = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
/**
* 向指定URL发送GET方法的请求
* 发送任务ID,返回任务详情
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
/*// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}*/
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 防止乱码
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 读写文件
*/
public static void rwFile(String outPath,String intPath){
FileWriter fw = null;
BufferedReader br = null;
try {
fw = new FileWriter(outPath, true);
br = new BufferedReader(new InputStreamReader(
new FileInputStream(intPath), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("文件内容: " + line);
fw.write(line);
fw.flush();
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 上传文件
* @param urlStr
* @param params 参数集合
* @param filePath 样本路径
* @return
* @throws UserException
*/
public static String formUpload(String urlStr, Map<String, String> textMap, String filePath) throws UserException {
String res = "";
HttpURLConnection conn = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
//conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 添加参数
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
System.out.println("strBuf.toString():"+strBuf.toString());
out.write(strBuf.toString().getBytes());
}
// file
File file = new File(filePath);
String filename = file.getName();
//获取文件类型
String contentType="text/plain";//默认类型
try {
MagicMatch match = Magic.getMagicMatch(file, false, true);
contentType = match.getMimeType();
} catch (Exception e) {
}
StringBuffer fileStrBuf = new StringBuffer();
fileStrBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
fileStrBuf.append("Content-Disposition: form-data; name=\"sampleFile\"; filename=\"" + filename + "\"\r\n");
fileStrBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(fileStrBuf.toString().getBytes());
DataInputStream 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);
}
in.close();
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
}