HttpURLConnection 发送http请求帮助类
生活随笔
收集整理的這篇文章主要介紹了
HttpURLConnection 发送http请求帮助类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
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请求帮助类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cocos2d-x android 入门
- 下一篇: 廖雪峰Java10加密与安全-4加密算法