用习惯了网络请求框架,有时候要自己写一个,有时候还是挺难的,然后就自己好好总结一下并记录。
Java get 请求
/**
* get 请求 可以传完整url,也可以传map
* 设置请求头 请求头的设置不关get post都可以设置不属于方法级别的区分 是协议的一部分
* @param url
* @param map
* @return
*/
private String get(String url, Map<String, String> map){
HttpURLConnection conn ;
BufferedReader in = null;
StringBuilder resultStr = new StringBuilder();
//get请求拼接请求参数 (当然可以可以直接传完整的路径)
// 这里可能会对value进行加密,比如base64 这里未考虑
//urlStr.append(URLEncoder.encode(entry.getValue(), "encoding"));
StringBuilder urlStr = new StringBuilder(url);
if (map != null && !map.isEmpty()){
for (Map.Entry<String, String> entry: map.entrySet()) {
urlStr.append(entry.getKey()).append("=");
//urlStr.append(URLEncoder.encode(entry.getValue(), "encoding"));
urlStr.append(entry.getValue());
urlStr.append("&");
}
urlStr.deleteCharAt(urlStr.length() - 1);
}
try {
URL realUrl = new URL(urlStr.toString());
conn = (HttpURLConnection) realUrl.openConnection();
//设置请求头 请求头的设置不关get post都可以设置不属于方法级别的区分 是协议的一部分
// conn.setRequestProperty("Accept", "text/plain, application/json, application/json, application/*+json, application/*+json, text/plain, */*, */*");
// conn.setRequestProperty("Access-Control-Allow-Origin", "mobcon.turkcell.com.tr");
// conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
// conn.setRequestProperty("Authorization", auth);
// 设置超时时间
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
// 开始连接网络 进行请求
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
if(conn.getResponseCode() == 200){
System.out.println("请求成功");
String line;
while ((line = in.readLine()) != null) {
resultStr.append(line);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return resultStr.toString();
}
注意:该代码中没有进行header 的相关属性设置,当你在使用的时候要注意服务器对这方面是否有要求,另外,对于参数的加密问题,这里指出了,没有进行加密,同样的要符合服务器需要。
Java post请求
private String post(String url, Map<String, String> map){
HttpURLConnection conn ;
BufferedReader in = null;
StringBuilder resultStr = new StringBuilder();
DataOutputStream dos = null;
// 这是post 的body
// 这里可能会对value进行加密,比如base64 这里未考虑
// urlStr.append(URLEncoder.encode(entry.getValue(), "encoding"));
StringBuilder urlParam = new StringBuilder();
try {
if (map != null && !map.isEmpty()){
for (Map.Entry<String, String> entry: map.entrySet()) {
urlParam.append(entry.getKey()).append("=");
//urlStr.append(URLEncoder.encode(entry.getValue(), "encoding"));
urlParam.append(entry.getValue());
urlParam.append("&");
}
urlParam.deleteCharAt(urlParam.length() - 1);
}
URL realUrl = new URL(url);
conn = (HttpURLConnection) realUrl.openConnection();
//设置请求头
//conn.setRequestProperty("Accept", "text/plain, application/json, application/json, application/*+json, application/*+json, text/plain, */*, */*");
// conn.setRequestProperty("Access-Control-Allow-Origin", "mobcon.turkcell.com.tr");
// conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
// conn.setRequestProperty("Authorization", auth);
conn.setRequestMethod("POST");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
dos = new DataOutputStream(conn.getOutputStream());
dos.write(urlParam.toString().getBytes());
dos.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
if(conn.getResponseCode() == 200){
System.out.println("请求成功");
String line;
while ((line = in.readLine()) != null) {
resultStr.append(line);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (dos != null) {
dos.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return resultStr.toString();
}
关注问题和get请求差不多,现在比较一下二者的区别(就api语法上来说),主要有:
- get不需要设置setDoInput ,setInput;
- post需要把请求体写入输出流并刷新
post文件上传
其实文件上传本质就是再把文件通过输入流写入,然后一起上传服务器,所以下面列出httpUrlConnection的文件上传标准代码
/**
* post 上传文件
* @param urlStr 服务器地址
* @param textMap 除文件外的字段 key value
* @param fileBytes 文件的二进制数组
* @param fileKey 文件的key
* @return
*/
public static String uploadFilePost(String urlStr, Map<String, String> textMap, String fileKey, byte[] fileBytes) {
String res = "";
HttpURLConnection conn = null;
// 这是一个分割符 ,也可以不要的
String BOUNDARY = "-----------file upload-------------";
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);
conn.setRequestProperty("Charset", "UTF-8");
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 对除了文件之外的参数进行拼接写入
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.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);
}
out.write(strBuf.toString().getBytes("UTF-8"));
}
// 对文件进行写入
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
// 写入文件的key ,name 和格式 form-data (如果不需要传name ,也可以不写,这里用xxxx 替代了)
strBuf.append("Content-Disposition: form-data; name=\""
+ fileKey + "\"; filename=\"" + "xxxx" + "\"\r\n");
strBuf.append("Content-Type:" +"application/octet-stream"+ "\r\n\r\n");
out.write(strBuf.toString().getBytes());
// 写入文件二进制数组
out.write(fileBytes);
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
// 读取正确返回信息
StringBuffer strBuf1 = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf1.append(line).append("\n");
}
res = strBuf1.toString();
reader.close();
reader = null;
}else{
// 读取错误返回信息
StringBuffer error = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String line1 = null;
while ((line1=bufferedReader.readLine())!=null) {
error.append(line1).append("\n");
}
res=error.toString();
bufferedReader.close();
bufferedReader=null;
}
} catch (Exception e) {
System.out.println("发送POST请求出错。" + e);
e.printStackTrace();
} finally {
//关闭流
if (conn != null) {
conn.disconnect();
conn = null;
}
}
//返回信息
return res;
}
/**
* post 上传文件
* @param urlStr 服务器地址
* @param textMap 除文件外的字段 key value
* @param fileMap 文件的key value 包括 每个文件的key,文件路径 可以上传多个文件
* @return
*/
public static String uploadFilePost(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) {
String res = "";
HttpURLConnection conn = null;
// 这是一个分割符 ,也可以不要的
String BOUNDARY = "-----------file upload-------------";
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);
conn.setRequestProperty("Charset", "UTF-8");
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 对除了文件之外的参数进行key value 拼接写入
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.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);
}
out.write(strBuf.toString().getBytes("UTF-8"));
}
if (fileMap != null) {
Iterator iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
// 文件的key
String inputName = (String) entry.getKey();
// 文件路径
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
//通过路径创建file
File file = new File(inputValue);
String filename = file.getName();
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
// 写入文件的key ,name 和格式 form-data (如果不需要传name ,也可以不写,这里用xxxx 替代了)
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" +"application/octet-stream"+ "\r\n\r\n");
out.write(strBuf.toString().getBytes());
// 写入文件二进制数组
DataInputStream in = new DataInputStream(new FileInputStream(file));
int fileBytes;
byte[] bufferOut = new byte[1024];
while ((fileBytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, fileBytes);
}
in.close();
}
}
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
// 读取正确返回信息
StringBuffer strBuf1 = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line ;
while ((line = reader.readLine()) != null) {
strBuf1.append(line).append("\n");
}
res = strBuf1.toString();
reader.close();
reader = null;
}else{
// 读取错误返回信息
StringBuffer error = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String line1 = null;
while ((line1=bufferedReader.readLine())!=null) {
error.append(line1).append("\n");
}
res=error.toString();
bufferedReader.close();
bufferedReader=null;
}
} catch (Exception e) {
System.out.println("发送POST请求出错。" + e);
e.printStackTrace();
} finally {
//关闭流
if (conn != null) {
conn.disconnect();
conn = null;
}
}
//返回信息
return res;
}
我提供了两个方法。第二个和第一个其实是一样的,当我们获取二进制数组方便时,就用第一个,或者把第二个的map的泛型改为byte数组,都是可以的。对比两个你就会发现,其实最终我们都是上传的是二进制数组,然后还要注意的是和服务端沟通好你们的上传协议,及相应的字段要求。明白了这种原生的请求,对于那些第三方网络请求库,我们需要看他背后的原理及其语法格式,对了在研究retrofit 和okhttp 结合这种常见的框架写法,后面还会继续出文章进行说明。
贴几个参考网站 ;;
另外,对于header 各种属性的设置和说明可以参考和你对接的服务平台,按要求设置即可。同时常见的属性和意义,参考