java 利用HttpURLConnection 发送http请求

提供GET / POST /上传文件/下载文件 功能

import java.io.*;
import java.net.*;
import java.util.Iterator;
import java.util.Map; import net.sf.jmimemagic.Magic;
import net.sf.jmimemagic.MagicMatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* Author: Administrator
*/
public class HttpHelper { private final static Logger logger = LoggerFactory.getLogger(HttpHelper.class); /**
* 发送get请求
*
* @param urlPath
* @return
*/
public static String get(String urlPath) { String res = "";
HttpURLConnection conn = null;
try {
URL url = new URL(urlPath);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int code = urlConnection.getResponseCode(); if (code == 200) {
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line); }
res = buffer.toString(); } } catch (Exception e) {
logger.error("发送get请求出错");
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
} return res;
} /**
* 发送post请求
*
* @param urlPath http://host:port/test.jsp
* @param postData name=abc&age=10
* @throws Exception
*/
public static String post(String urlPath, String postData) { HttpURLConnection conn = null;
String res = ""; try {
//建立连接
URL url = new URL(urlPath); conn = (HttpURLConnection) url.openConnection();
//设置参数
conn.setDoOutput(true); //需要输出
conn.setDoInput(true); //需要输入
conn.setUseCaches(false); //不允许缓存
conn.setRequestMethod("POST"); //设置POST方式连接 //设置请求属性
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
conn.setRequestProperty("Charset", "UTF-8"); //连接,也可以不用明文connect,使用下面的httpConn.getOutputStream()会自动connect
conn.connect(); //建立输入流,向指向的URL传入参数
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(postData.getBytes("utf-8"));
dos.flush();
dos.close(); //获得响应状态
int resultCode = conn.getResponseCode();
if (HttpURLConnection.HTTP_OK == resultCode) {
StringBuffer sb = new StringBuffer();
String readLine = new String();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
}
responseReader.close();
res = sb.toString();
}
} catch (Exception e) {
logger.error("发送POST请求出错。" + urlPath);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
} return res;
} /**
* 发送post 数据为json
*
* @param urlPath
* @param Json
* @return
* @throws Exception
*/
public static String postJson(String urlPath, String Json) { HttpURLConnection conn = null;
String res = ""; try {
//建立连接
URL url = new URL(urlPath);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
// 设置文件类型:
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// 设置接收类型否则返回415错误
//conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型,以此来防范返回415;
conn.setRequestProperty("accept", "application/json");
// 往服务器里面发送数据 byte[] writebytes = Json.getBytes();
// 设置文件长度
conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
OutputStream outwritestream = conn.getOutputStream();
outwritestream.write(Json.getBytes("utf-8"));
outwritestream.flush();
outwritestream.close(); if (conn.getResponseCode() == 200) {
StringBuffer sb = new StringBuffer();
String readLine = new String();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((readLine = bufferedReader.readLine()) != null) {
sb.append(readLine).append("\n");
}
bufferedReader.close();
res = sb.toString();
}
} catch (Exception e) {
logger.error("发送POST请求出错。" + urlPath);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
} return res;
} /**
* formupload方式提交数据
*
* @param urlPath
* @param textMap 表单字段
* @param fileMap 文件列表
* @return
*/
public static String formUpload(String urlPath, Map<String, String> textMap, Map<String, String> fileMap) {
String res = "";
HttpURLConnection conn = null;
String BOUNDARY = "----lwm12345boundary"; //boundary就是request头和上传文件内容的分隔符
try {
URL url = new URL(urlPath);
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());
// text
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);
}
out.write(strBuf.toString().getBytes("utf-8"));
} // file
if (fileMap != null) {
Iterator<Map.Entry<String, String>> iter = fileMap.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;
}
File file = new File(inputValue);
String filename = file.getName();
MagicMatch match = Magic.getMagicMatch(file, false, true);
String contentType = match.getMimeType(); StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); out.write(strBuf.toString().getBytes("utf-8")); 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) {
logger.error("发送POST请求出错。" + urlPath);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
} /**
* 发送下载文件请求
*
* @param urlPath
* @param downloadDir
* @return
*/
public static File downloadFile(String urlPath, String downloadDir) {
File file = null;
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
// 设定请求的方法,默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect(); // 文件大小
int fileLength = httpURLConnection.getContentLength(); // 文件名
String filePathUrl = httpURLConnection.getURL().getFile();
String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1); System.out.println("file length---->" + fileLength); URLConnection con = url.openConnection(); BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream()); String path = downloadDir + File.separatorChar + fileFullName;
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[1024];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
// 打印下载百分比
// System.out.println("下载了-------> " + len * 100 / fileLength +
// "%\n");
}
bin.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
return file;
} }
}

  

HttpURLConnection 发送http请求帮助类的更多相关文章

  1. HttpURLConnection发送POST请求(可包含文件)

    import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io. ...

  2. HttpUrlConnection发送url请求(后台springmvc)

    1.HttpURLConnection发送url请求 public class JavaRequest { private static final String BASE_URL = "h ...

  3. 【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法(一)

    Java原生的API可用于发送HTTP请求 即java.net.URL.java.net.URLConnection,JDK自带的类: 1.通过统一资源定位器(java.net.URL)获取连接器(j ...

  4. Java利用原始HttpURLConnection发送http请求数据小结

    1,在post请求下,写输出应该在读取之后,否则会抛出异常. 即操作OutputStream对象应该在InputStreamReader之前. 2.conn.getResponseCode()获取返回 ...

  5. 利用HttpURLConnection发送post请求上传多个文件

    本文要用java.net.HttpURLConnection来实现多个文件上传 1. 研究 form 表单到底封装了什么样的信息发送到servlet. 假如我参数写的内容是hello word,然后二 ...

  6. Java 发送 Https 请求工具类 (兼容http)

    依赖 jsoup-1.11.3.jar <dependency> <groupId>org.jsoup</groupId> <artifactId>js ...

  7. 接口使用Http发送post请求工具类

    HttpClientKit import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamR ...

  8. Java 发送 Http请求工具类

    HttpClient.java package util; import java.io.BufferedReader; import java.io.IOException; import java ...

  9. HttpURLConnection 发送PUT请求 json请求体 与服务端接收

    发送请求: public void testHttp() { String result = ""; try { URL postURL = new URL("http: ...

随机推荐

  1. 解决input 中placeholder的那些神坑

    **昨天后台小哥哥提到placehold无法显示问题,我这边总结一下,顺便写个小文章分享给大家..** ============================================== 一 ...

  2. keep-alive 组件级缓存

    前言 在Vue构建的单页面应用(SPA)中,路由模块一般使用vue-router.vue-router不保存被切换组件的状态, 它进行push或者replace时,旧组件会被销毁,而新组件会被新建,走 ...

  3. 导入Excel扩展名是.xls 和.xlsx的

    1.首先是导入Excel2003以前(包括2003)的版本,扩展名是.xls 的 /** * 操作Excel2003以前(包括2003)的版本,扩展名是.xls * @param templetFil ...

  4. 在postman中请求的接口有csrf怎么办

    今天在写项目的时候,写了一个post接口,为了防止crsf攻击,config.defalut.js文件中加了如下代码: exports.security = { csrf: { ignoreJSON: ...

  5. mysql ALTER TABLE语句 语法

    mysql ALTER TABLE语句 语法 作用:用于在已有的表中添加.修改或删除列.无铁芯直线电机 语法:添加列:ALTER TABLE table_name ADD column_name da ...

  6. java+web+超大文件上传

    javaweb上传文件 上传文件的jsp中的部分 上传文件同样可以使用form表单向后端发请求,也可以使用 ajax向后端发请求 1.通过form表单向后端发送请求 <form id=" ...

  7. FJWC2017&FJOI2017一试 游记

    day1 ​ 早上是以前泉州七中的杨国烨讲课.(据说当时看新闻说是一对双胞胎一起上thu的其中一个)课题是图论/网络流. ​ 下午第一道一开始推出来了一个之和面积有关的式子,然后觉得可以容斥一发,觉得 ...

  8. 【bzoj3223】Tyvj 1729 文艺平衡树

    题目描述: 您需要写一种数据结构(可参考题目标题),来维护一个有序数列,其中需要提供以下操作:翻转一个区间,例如原有序序列是5 4 3 2 1,翻转区间是[2,4]的话,结果是5 2 3 4 1 输入 ...

  9. androi自定义自动换行的View(类似网页的标签Tag)

    看来只有礼拜天才有时间写点博客啊,平时只能埋头苦干了.今天在公司加班,遇到一个需求,就是自动换行的TextView,有点像网页的tag标签,点击一下,就自动加上去了,不过这个是根据后台拿来的数据来显示 ...

  10. ACM ICPC 2011-2012 Northeastern European Regional Contest(NEERC)B Binary Encoding

    B: 现在有一种新的2进制表示法,要你求出0~m-1的每个数的表示. 规则如下:n 是满足 m<=2n 最小数. 而0~m-1的数只能够用n-1个位和n个位来表示. 对于n个位表示的数来说不能有 ...