利用HttpUrlConnection使用
package test;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* <p>Title: HttpUtil</p>
* 描述: 通过HttpURLConnection封装http请求
* @author:邢延明
* @date: 2019年8月19日 下午3:52:34
*/
public class HttpUtil {
static String BOUNDARY = java.util.UUID.randomUUID().toString();
static String TWO_HYPHENS = "--";
static String LINE_END = "\r\n";
/**
* 方法名: sendGet
* 描述: 封装get请求
* @param target
* @return
* @throws Exception String
* 时间: 2019年8月19日 下午5:18:50
*/
public static String sendGet( String target) throws Exception {
String httpresult = null;
try{
//1.设置请求的网址
URL url = new URL(target);
//2.获取连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3.设置请求方法
conn.setRequestMethod("GET");
//设置连接超时时间
conn.setConnectTimeout(1000 * 60);
//设置读取超时时间
conn.setReadTimeout(1000 * 60);
//允许写出
conn.setDoOutput(true);
//允许读入
conn.setDoInput(true);
conn.connect();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inStream=conn.getInputStream();
//将读入内容转换成字符串
httpresult = new String(readInputStream(inStream), "UTF-8");
}
}catch(Exception e){
throw e;
}
return httpresult;
}
/**
* 方法名: sendPost
* 描述: 正常post请求
* @param message
* @param target
* @throws Exception String
* 时间: 2019年8月19日 下午3:52:12
*/
public static String sendPost(String message, String target) throws Exception {
String httpresult = null;
try{
//1.设置请求的网址
URL url = new URL(target);
//2.获取连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3.设置请求方法
conn.setRequestMethod("POST");
//设置连接超时时间
conn.setConnectTimeout(1000 * 60);
//设置读取超时时间
conn.setReadTimeout(1000 * 60);
//允许写出
conn.setDoOutput(true);
//允许读入
conn.setDoInput(true);
conn.connect();
byte[] bypes = message.toString().getBytes("UTF-8");
conn.getOutputStream().write(bypes);
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inStream=conn.getInputStream();
//将读入内容转换成字符串
httpresult = new String(readInputStream(inStream), "UTF-8");
}
}catch(Exception e){
throw e;
}
return httpresult;
}
/**
* 方法名: sendPost
* 描述: 发送json数据
* @param message
* @param target
* @return
* @throws Exception String
* 时间: 2019年8月19日 下午4:03:24
*/
public static String sendPostJson(String message, String target) {
String httpresult = null;
try{
//1.设置请求的网址
URL url = new URL(target);
//2.获取连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3.设置请求方法
conn.setRequestMethod("POST");
//设置连接超时时间
conn.setConnectTimeout(1000 * 60);
//设置读取超时时间
conn.setReadTimeout(1000 * 60);
//设置请求头
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//允许写出
conn.setDoOutput(true);
//允许读入
conn.setDoInput(true);
conn.connect();
byte[] bypes = message.toString().getBytes("UTF-8");
conn.getOutputStream().write(bypes);
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inStream=conn.getInputStream();
//将读入内容转换成字符串
httpresult = new String(readInputStream(inStream), "UTF-8");
}
}catch(Exception e){
e.printStackTrace();
}
return httpresult;
}
/**
* 方法名: sendFile
* 描述: 表单文件上传,可以自己通过两个循环完成多文件,多参数上传。
* @param fileName
* @param target
* @return String
* 时间: 2019年8月19日 下午5:19:30
*/
public static String sendFile(String fileName, String target) {
String httpresult = null;
try{
//1.设置请求的网址
URL url = new URL(target);
//2.获取连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3.设置请求方法
conn.setRequestMethod("POST");
//设置连接超时时间
//conn.setConnectTimeout(1000 * 60);
//设置读取超时时间
//conn.setReadTimeout(1000 * 60);
//设置请求头
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type","multipart/form-data; BOUNDARY=" + BOUNDARY);
//允许写出
conn.setDoOutput(true);
//允许读入
conn.setDoInput(true);
conn.connect();
File file = new File(fileName);
//file.
//此处使用一个循环就可完成多文件的上传
StringBuffer strBufFile = new StringBuffer();
strBufFile.append(LINE_END);
strBufFile.append(TWO_HYPHENS);
strBufFile.append(BOUNDARY);
strBufFile.append(LINE_END);
strBufFile.append("Content-Disposition: form-data; name=\"uploadFile\"; filename=\"" + file.getName() + "\"");
strBufFile.append(LINE_END);
//strBufFile.append("Content-Type: " + "image/*" );
strBufFile.append(LINE_END);
strBufFile.append("Content-Lenght: "+file.length());
strBufFile.append(LINE_END);
strBufFile.append(LINE_END);
//OutputStream outputStream = conn.getOutputStream();
DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
//此处使用一个循环就可以完成多个文件域的上传.
StringBuffer strBufparam = new StringBuffer();
strBufparam.append(TWO_HYPHENS);
strBufparam.append(BOUNDARY);
strBufparam.append(LINE_END);
strBufparam.append("Content-Disposition: form-data; name=\"name\"");
strBufparam.append(LINE_END);
strBufparam.append("Content-Type: " + "text/plain" );
strBufparam.append(LINE_END);
strBufparam.append("Content-Lenght: "+("1232").length());
strBufparam.append(LINE_END);
strBufparam.append(LINE_END);
strBufparam.append(""+1232);
//strBufparam.append(LINE_END);
outputStream.write(strBufparam.toString().getBytes());
outputStream.write(strBufFile.toString().getBytes());
FileInputStream fileInputStream = new FileInputStream(file);//把文件封装成一个流
int length = -1;
byte[] bytes = new byte[1024];
while ((length = fileInputStream.read(bytes)) != -1){
outputStream.write(bytes,0,length);//写的具体操作
}
//写入标记结束位
byte[] endData = (LINE_END + TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + LINE_END).getBytes();//写结束标记位
outputStream.write(endData);
outputStream.flush();
fileInputStream.close();
outputStream.close();
//conn.getOutputStream().write(bypes);
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inStream=conn.getInputStream();
//将读入内容转换成字符串
httpresult = new String(readInputStream(inStream), "UTF-8");
}
}catch(Exception e){
e.printStackTrace();
}
return httpresult;
}
public static void main(String[] args) throws Exception {
/*String sendPostJson = sendPostJson("{\"subject\":\"CN=社保秘密什么的次数程度, OU=!人力资源和社会保障局420181130110140917, [email protected], L=沈阳, S=辽宁, C=CN\",\"certBody\":\"\",\"sn\":\"\",\"license\":\"10dfa8c6-9a4f-4d84-bffe-7bb5c5f1506c\"}","http://seal.gxaq.com.cn/get/stampByCert");
System.out.println(123);
System.out.println(sendPostJson);*/
/*String sendFile = sendFile("E:/tmp/694.png", "http://192.168.1.150:8080/upload");
System.out.println(sendFile);*/
/*String sendGet = sendGet("http://www.baidu.com");
System.out.println(sendGet);*/
}
/**
* 方法名: readInputStream
* 描述: 读取输入流中的字符串
* @param inStream
* @return 输入流中的字节数组
* @throws Exception byte[]
* 时间: 2019年8月19日 下午3:54:10
*/
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = inStream.read(buffer)) !=-1 ){
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inStream.close();
return data;
}
}