您的位置:首页 > 理论基础 > 计算机网络

HttpURLConnection实现HttpClient工具类(get/post请求,文件上传)

2017-11-29 11:48 841 查看
本博客简单介绍一下HttpURLConnection实现的POST和GET请求以及文件上传,还有文件上传的服务器代码实现。

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.HttpResponseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClient {
protected final static Logger logger = LoggerFactory.getLogger(HttpClient.class);

/**
* Description:文件上传,以及可以传递参数,支持文件批量上传
*
* @param actionUrl 请求地址
* @param params 参数
* @param files 多个文件
* @return
* @throws Exception
*/
public static Map<String, Object> post(String actionUrl, Map<String, String> params, Map<String, File> files)
throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
logger.info("post file url:" + actionUrl + " params:" + params);
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";

URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(10 * 1000); // cache max time
conn.setConnectTimeout(5*1000);
conn.setDoInput(true);// allow input
conn.setDoOutput(true);// allow output
conn.setUseCaches(false); // cache is disable
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// construct params for Text
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}

DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes("utf-8"));
// send data
if (files != null) {
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\""
+ file.getValue() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());

InputStream is = new FileInputStream(file.getValue());
try {
byte[] buffer = new byte[(int) file.getValue().length()];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
} catch (Exception e) {
throw e;
} finally {
is.close();
outStream.write(LINEND.getBytes());
}

}
}

// the finsh flag
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();

// get response
int res = conn.getResponseCode();
map.put("status", res);
InputStream in = null;
String result = null;
switch (res) {
case 200:
in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
result = sb2.toString();
map.put("returnString", result);
break;
case 403:
throw new HttpResponseException(res, "request forbided");
case 404:
throw new HttpResponseException(res, "not fonud such address");
default:
throw new Exception("undefine error:" + res);
}
conn.disconnect();
return map;
}

public static String post(String actionUrl, Map<String, String> params) throws Exception {
String contentType = "application/x-www-form-urlencoded";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000); // Cache max time
conn.setConnectTimeout(5*1000);
conn.setDoInput(true);// allow input
conn.setDoOutput(true);// Allow output
conn.setUseCaches(false); // cache is disable
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", contentType);
StringBuilder sb = new StringBuilder();

for (Map.Entry<String, String> entry : params.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(entry.getKey());
sb.append("=");
sb.append(URLEncoder.encode(entry.getValue()));
}
OutputStream output = conn.getOutputStream();
output.write(sb.toString().getBytes());
output.flush();

int res = conn.getResponseCode();
InputStream in = null;
String result = null;
switch (res) {
case 200:
in = conn.getInputStream();
String line;
StringBuilder sb2 = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
while ((line = bufferedReader.readLine()) != null) {
sb2.append(line);
}
result = sb2.toString();
break;
case 403:
throw new HttpResponseException(res, "request forbided");
case 404:
throw new HttpResponseException(res, "not fonud such address");
default:
throw new Exception("undefine error:" + res);
}
return result;
}

public static String get(String actionUrl, Map<String, String> params) throws Exception {
String contentType = "application/x-www-form-urlencoded";

StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(entry.getKey());
sb.append("=");
sb.append(URLEncoder.encode(entry.getValue()));
}
if (actionUrl.endsWith("?")) {
actionUrl += sb.toString();
} else {
actionUrl += "?" + sb.toString();
}
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000); // Cache max time
conn.setDoInput(true);// allow input
conn.setDoOutput(true);// Allow output
conn.setUseCaches(false); // cache is disable
conn.setRequestMethod("GET");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", contentType);

int res = conn.getResponseCode();
// Log.i("le_assistant","actionUrl:" +actionUrl+" ResponseCode:"+res);
InputStream in = null;
String result = null;
switch (res) {
case 200:
in = conn.getInputStream();
String line;
StringBuilder sb2 = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
while ((line = bufferedReader.readLine()) != null) {
sb2.append(line);
}
result = sb2.toString();
break;
case 403:
throw new HttpResponseException(res, "request forbided");
case 404:
throw new HttpResponseException(res, "not fonud such address");
default:
throw new Exception("undefine error:" + res);
}
return result;
}

public static void main(String[] args) {
String url = "http://localhost:8990/file/Upload";
Map<String,String> params = new HashMap<String, String>();
Map<String, File> files = new HashMap<String, File>();
File file = new File("d:\\a.png");
files.put("file", file);

try {
System.out.println(post(url, params,files));
} catch (Exception e) {
e.printStackTrace();
}
}

}


文件上传的服务器代码实现(Java):
@RestController
@RequestMapping("/file")
public class FileUploadController {

/**
* 图片上传
* @param file
* @return
*/
@RequestMapping("/upload")
@ResponseBody
public Object fileUpload(@RequestParam(value = "file", required = false) MultipartFile file){
JSONObject object = new JSONObject();
try {
if(file!=null){
//保存文件
String fileName = file.getOriginalFilename();
String fileExt = getExtention(fileName);
byte[] fileByte = file.getBytes();
//文件处理

}
} catch (IOException e) {
e.printStackTrace();
}
return object;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息