HTTP網(wǎng)絡(luò)通信工具

HttpUtil



package com.xyy.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HttpUtil {

  /**
    * http請(qǐng)求的get方式
    *
    * @param http
    * @return
    */
  public static String get(String http) {
      String result = null;
      try {
        URL url = new URL(http);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (conn.getResponseCode() == 200) {
            // 獲取服務(wù)器端返回內(nèi)容的輸入流
            InputStream in = conn.getInputStream();
            // 創(chuàng)建內(nèi)容輸出流(作用是臨時(shí)存儲(chǔ)內(nèi)容然后轉(zhuǎn)為byte數(shù)組)
            ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int num;
            while ((num = in.read(buffer)) != -1) {
              dataOut.write(buffer, 0, num);
            }
            dataOut.flush();
            result = new String(dataOut.toByteArray());
            dataOut.close();
            in.close();
        }
        conn.disconnect();
      } catch (Exception e) {

      }
      return result;
  }

  /**
    * http的post請(qǐng)求
    *
    * @param http 請(qǐng)求地址
    * @param map 請(qǐng)求參數(shù)列表
    * @return
    */
  public static String post(String http, Map<String, String> map) {
      String result = null;
      try {
        URL url = new URL(http);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setConnectTimeout(30000);
        // 設(shè)置請(qǐng)求方式為post
        conn.setRequestMethod("POST");
        conn.connect();
        if (map != null) {
            // 提交參數(shù)
            StringBuffer sb = new StringBuffer();
            Iterator<Entry<String, String>> it = map.entrySet().iterator();
            while (it.hasNext()) {
              Entry<String, String> entry = it.next();
              sb.append(entry.getKey()).append("=")
                    .append(entry.getValue()).append("&");
            }
            // 將最后一個(gè)&去掉
            sb.delete(sb.length() - 1, sb.length());
            String par = sb.toString();
            OutputStreamWriter out = new OutputStreamWriter(
                  conn.getOutputStream(), "UTF-8");
            out.write(par);
            out.flush();
            out.close();
        }
        // 判斷是否連接成功
        if (conn.getResponseCode() == 200) {
            InputStream in = conn.getInputStream();
            ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int num;
            while ((num = in.read(buffer)) != -1) {
              dataOut.write(buffer, 0, num);
            }
            dataOut.flush();
            result = new String(dataOut.toByteArray());
            in.close();
            dataOut.close();
        }
        conn.disconnect();
      } catch (Exception e) {

      }
      return result;
  }

  public static String post(String actionUrl, Map<String, String> params,
                      Map<String, File> files) {
      return post(actionUrl, params, files, null);
  }

  // 上傳代碼稀轨,第一個(gè)參數(shù)炭玫,為要使用的URL,第二個(gè)參數(shù)思瘟,為表單內(nèi)容桥滨,第三個(gè)參數(shù)為要上傳的文件潮针,可以上傳多個(gè)文件
  public static String post(String actionUrl, Map<String, String> params,
                      Map<String, File> files, OnUploadListener l) {
      if (null == files) {
        return post(actionUrl, params);
      }
      String result = null;
      try {
        // 將內(nèi)容以二進(jìn)制流形式提交到服務(wù)器(需要服務(wù)器單獨(dú)解析)
        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();
        // 讀取超時(shí)的設(shè)置
        conn.setReadTimeout(5 * 1000);
        conn.setDoInput(true);// 允許輸入
        conn.setDoOutput(true);// 允許輸出
        conn.setUseCaches(false);
        conn.setRequestMethod("POST"); // Post方式
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
              + ";boundary=" + BOUNDARY);
        // 組裝文本類型參數(shù)列表
        StringBuilder sb = new StringBuilder();
        if (null != params) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
              sb.append(PREFIX);
              sb.append(BOUNDARY);
              sb.append(LINEND);
              // 傳遞文本參數(shù)的key部分
              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);
              // 傳遞文本參數(shù)的value部分
              sb.append(entry.getValue());
              sb.append(LINEND);
            }
        }
        DataOutputStream outStream = new DataOutputStream(
              conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        // 發(fā)送文件數(shù)據(jù)
        if (files != null) {
            int totalSize = 0;
            int currentSize = 0;
            for (Map.Entry<String, File> file : files.entrySet()) {
              totalSize += file.getValue().length();
            }
            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\"; filename=\""
                    + file.getKey() + "\"" + LINEND);
              sb1.append("Content-Type: multipart/form-data; charset="
                    + CHARSET + LINEND);
              sb1.append(LINEND);
              outStream.write(sb1.toString().getBytes());
              InputStream is = new FileInputStream(file.getValue());
              byte[] buffer = new byte[1024];
              int len = 0;
              while ((len = is.read(buffer)) != -1) {
                  outStream.write(buffer, 0, len);
                  // 上傳進(jìn)度的計(jì)算
                  currentSize += len;
                  if (null != l) {
                    l.onProgress(currentSize, totalSize);
                  }
              }
              is.close();
              outStream.write(LINEND.getBytes());
            }
        }
        // 請(qǐng)求結(jié)束標(biāo)志
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        // 判斷是否連接成功
        if (conn.getResponseCode() == 200) {
            InputStream in = conn.getInputStream();
            ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int num;
            while ((num = in.read(buffer)) != -1) {
              dataOut.write(buffer, 0, num);
            }
            dataOut.flush();
            result = new String(dataOut.toByteArray());
            in.close();
            dataOut.close();
        }
        conn.disconnect();
      } catch (Exception e) {
        e.printStackTrace();
      }
      return result;
  }

  public interface OnUploadListener {
      void onProgress(int current, int total);
  }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末暖哨,一起剝皮案震驚了整個(gè)濱河市畏吓,隨后出現(xiàn)的幾起案子滚婉,更是在濱河造成了極大的恐慌图筹,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,386評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件让腹,死亡現(xiàn)場(chǎng)離奇詭異远剩,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)骇窍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門瓜晤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人腹纳,你說我怎么就攤上這事痢掠。” “怎么了嘲恍?”我有些...
    開封第一講書人閱讀 164,704評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵足画,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我佃牛,道長(zhǎng)淹辞,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,702評(píng)論 1 294
  • 正文 為了忘掉前任俘侠,我火速辦了婚禮象缀,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘爷速。我一直安慰自己央星,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,716評(píng)論 6 392
  • 文/花漫 我一把揭開白布遍希。 她就那樣靜靜地躺著等曼,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上禁谦,一...
    開封第一講書人閱讀 51,573評(píng)論 1 305
  • 那天胁黑,我揣著相機(jī)與錄音,去河邊找鬼州泊。 笑死丧蘸,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的遥皂。 我是一名探鬼主播力喷,決...
    沈念sama閱讀 40,314評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼演训!你這毒婦竟也來了弟孟?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,230評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤样悟,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后窟她,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,680評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡录肯,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,873評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了吊说。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片论咏。...
    茶點(diǎn)故事閱讀 39,991評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡疏叨,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出蚤蔓,到底是詐尸還是另有隱情,我是刑警寧澤糊余,帶...
    沈念sama閱讀 35,706評(píng)論 5 346
  • 正文 年R本政府宣布秀又,位于F島的核電站,受9級(jí)特大地震影響贬芥,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜昏苏,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,329評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望贤惯。 院中可真熱鬧,春花似錦屁商、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至毒坛,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間屡谐,已是汗流浹背蝌数。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留饵撑,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,158評(píng)論 3 370
  • 正文 我出身青樓滑潘,卻偏偏與公主長(zhǎng)得像锨咙,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子粹舵,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,941評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容