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());// textif (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"));}// fileif (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;// 设定请求的方法,默认是GEThttpURLConnection.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;}}
}

  

转载于:https://www.cnblogs.com/liuxm2017/p/10869590.html

HttpURLConnection 发送http请求帮助类相关推荐

  1. HttpURLConnection发送post请求

    HttpURLConnection发送post请求 package main.utils;import java.io.*; import java.net.HttpURLConnection; im ...

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

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

  3. HttpURLConnection 发送post请求。并将结果以JSONObject对象返回的轮子

    Android新版sdk废除了对Apache的HttpClient.以前写的发送Http请求的轮子不能用了.所以用java底层支持的HttpURLConnection类重新造了一个轮子. 虽然Goog ...

  4. java的connect和http_【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法

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

  5. 用HttpURLConnection发送http请求

    //发送http请求 try { //1.使用网址构造一个URL对象 URL url = new URL(path); //2.获取连接对象 HttpURLConnection conn = (Htt ...

  6. Java 发送 Http请求工具类

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

  7. android发送网络请求没反应,Android无法使用HttpURLConnection发送GET请求

    我正在尝试在我的应用程序中使用HttpURLConnection.我将我的请求方法设置为'GET',但是当我尝试检索输出流时,该方法将更改为'POST'! 我不确定是什么原因,但是当我使用'POST' ...

  8. C# 发送Http请求 - WebClient类

    WebClient位于System.Net命名空间下,通过这个类可以方便的创建Http请求并获取返回内容. 一.用法1 - DownloadData string uri = "http:/ ...

  9. HttpURLConnection发送post请求信息

    public static void testHttpQuest() {// {'pfxInfo':'no','isPfx':'no','signInfo':'中文','passCode':'','s ...

最新文章

  1. pointnet与pointnet++
  2. 51nod1429 巧克力
  3. tensorflow 滑动平均使用和恢复
  4. 面向对象思想精华总结
  5. 2009我的lamp之路
  6. zabbix专题:第六章 动作Actions、告警方式Medias
  7. 【转】IT从业人员必看的10个论坛
  8. 第 7 章 Neutron - 073 - Service Plugin / Agent
  9. Zigbee协议栈无线通信系统
  10. (20210116已解决)Windows下的CTF加载程序是什么?
  11. java hash 数组_Java数组 哈希表 属性类 -解道Jdon
  12. 用select多路io复用实现简单聊天程序
  13. 在控制台程序中隐藏控制台窗口!
  14. 物联网介绍の高屋建瓴篇
  15. matlab之直方图的绘制
  16. wave.Error: unknown format: 3解决方法
  17. 谈谈对MVVM的理解?
  18. Flash进度条ProgressBar
  19. 楼宇对讲朝智能家居成长 可从多角度切入
  20. MIT JOS 6.828 Lab1学习笔记

热门文章

  1. SqlDataAdapter.Update批量数据更新
  2. MindManager 报错:Click to restart mindjet player 解决方法
  3. 要是想让程序跳转到绝对地址是0x100000去执行
  4. 怎样为ubuntu eclipse 添加 GBK字符集
  5. linux中的umask 函数
  6. button按钮跳转JS代码
  7. 园林空气净化器永久测试版
  8. Android ListView滑动后背景变黑
  9. ios command
  10. 2019牛客暑期多校训练营(第七场)A String(暴力)