Java中http請求的三種方式

這是第一種方式:

package com.powerX.httpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {
  public static String doGet(String httpurl) {
    HttpURLConnection connection = null;
    InputStream is = null;
    BufferedReader br = null;
    String result = null;// 返回結果字符串
    try {
      // 創建遠程url連接對象
      URL url = new URL(httpurl);
      // 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類
      connection = (HttpURLConnection) url.openConnection();
      // 設置連接方式:get
      connection.setRequestMethod("GET");
      // 設置連接主機服務器的超時時間:15000毫秒
      connection.setConnectTimeout(15000);
      // 設置讀取遠程返回的數據時間:60000毫秒
      connection.setReadTimeout(60000);
      // 發送請求
      connection.connect();
      // 通過connection連接,獲取輸入流
      if (connection.getResponseCode() == 200) {
        is = connection.getInputStream();
        // 封裝輸入流is,並指定字符集
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        // 存放數據
        StringBuffer sbf = new StringBuffer();
        String temp = null;
        while ((temp = br.readLine()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 關閉資源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      connection.disconnect();// 關閉遠程連接
    }

    return result;
  }

  public static String doPost(String httpUrl, String param) {

    HttpURLConnection connection = null;
    InputStream is = null;
    OutputStream os = null;
    BufferedReader br = null;
    String result = null;
    try {
      URL url = new URL(httpUrl);
      // 通過遠程url連接對象打開連接
      connection = (HttpURLConnection) url.openConnection();
      // 設置連接請求方式
      connection.setRequestMethod("POST");
      // 設置連接主機服務器超時時間:15000毫秒
      connection.setConnectTimeout(15000);
      // 設置讀取主機服務器返回數據超時時間:60000毫秒
      connection.setReadTimeout(60000);

      // 默認值爲:false,當向遠程服務器傳送數據/寫數據時,需要設置爲true
      connection.setDoOutput(true);
      // 默認值爲:true,當前向遠程服務讀取數據時,設置爲true,該參數可有可無
      connection.setDoInput(true);
      // 設置傳入參數的格式:請求參數應該是 name1=value1&name2=value2 的形式。
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      // 設置鑑權信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
      connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
      // 通過連接對象獲取一個輸出流
      os = connection.getOutputStream();
      // 通過輸出流對象將參數寫出去/傳輸出去,它是通過字節數組寫出的
      os.write(param.getBytes());
      // 通過連接對象獲取一個輸入流,向遠程讀取
      if (connection.getResponseCode() == 200) {

        is = connection.getInputStream();
        // 對輸入流對象進行包裝:charset根據工作項目組的要求來設置
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuffer sbf = new StringBuffer();
        String temp = null;
        // 循環遍歷一行一行讀取數據
        while ((temp = br.readLine()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 關閉資源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != os) {
        try {
          os.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 斷開與遠程地址url的連接
      connection.disconnect();
    }
    return result;
  }
}

這是第二種方式

package com.powerX.httpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClient3 {

  public static String doGet(String url) {
    // 輸入流
    InputStream is = null;
    BufferedReader br = null;
    String result = null;
    // 創建httpClient實例
    HttpClient httpClient = new HttpClient();
    // 設置http連接主機服務超時時間:15000毫秒
    // 先獲取連接管理器對象,再獲取參數對象,再進行參數的賦值
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 創建一個Get方法實例對象
    GetMethod getMethod = new GetMethod(url);
    // 設置get請求超時爲60000毫秒
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    // 設置請求重試機制,默認重試次數:3次,參數設置爲true,重試機制可用,false相反
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
    try {
      // 執行Get方法
      int statusCode = httpClient.executeMethod(getMethod);
      // 判斷返回碼
      if (statusCode != HttpStatus.SC_OK) {
        // 如果狀態碼返回的不是ok,說明失敗了,打印錯誤信息
        System.err.println("Method faild: " + getMethod.getStatusLine());
      } else {
        // 通過getMethod實例,獲取遠程的一個輸入流
        is = getMethod.getResponseBodyAsStream();
        // 包裝輸入流
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuffer sbf = new StringBuffer();
        // 讀取封裝的輸入流
        String temp = null;
        while ((temp = br.readLine()) != null) {
          sbf.append(temp).append("\r\n");
        }

        result = sbf.toString();
      }

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 關閉資源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 釋放連接
      getMethod.releaseConnection();
    }
    return result;
  }

  public static String doPost(String url, Map<String, Object> paramMap) {
    // 獲取輸入流
    InputStream is = null;
    BufferedReader br = null;
    String result = null;
    // 創建httpClient實例對象
    HttpClient httpClient = new HttpClient();
    // 設置httpClient連接主機服務器超時時間:15000毫秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 創建post請求方法實例對象
    PostMethod postMethod = new PostMethod(url);
    // 設置post請求超時時間
    postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);

    NameValuePair[] nvp = null;
    // 判斷參數map集合paramMap是否爲空
    if (null != paramMap && paramMap.size() > 0) {// 不爲空
      // 創建鍵值參數對象數組,大小爲參數的個數
      nvp = new NameValuePair[paramMap.size()];
      // 循環遍歷參數集合map
      Set<Entry<String, Object>> entrySet = paramMap.entrySet();
      // 獲取迭代器
      Iterator<Entry<String, Object>> iterator = entrySet.iterator();

      int index = 0;
      while (iterator.hasNext()) {
        Entry<String, Object> mapEntry = iterator.next();
        // 從mapEntry中獲取key和value創建鍵值對象存放到數組中
        try {
          nvp[index] = new NameValuePair(mapEntry.getKey(),
              new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        index++;
      }
    }
    // 判斷nvp數組是否爲空
    if (null != nvp && nvp.length > 0) {
      // 將參數存放到requestBody對象中
      postMethod.setRequestBody(nvp);
    }
    // 執行POST方法
    try {
      int statusCode = httpClient.executeMethod(postMethod);
      // 判斷是否成功
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method faild: " + postMethod.getStatusLine());
      }
      // 獲取遠程返回的數據
      is = postMethod.getResponseBodyAsStream();
      // 封裝輸入流
      br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

      StringBuffer sbf = new StringBuffer();
      String temp = null;
      while ((temp = br.readLine()) != null) {
        sbf.append(temp).append("\r\n");
      }

      result = sbf.toString();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 關閉資源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 釋放連接
      postMethod.releaseConnection();
    }
    return result;
  }
}

這是第三種方式

package com.powerX.httpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClient3 {

  public static String doGet(String url) {
    // 輸入流
    InputStream is = null;
    BufferedReader br = null;
    String result = null;
    // 創建httpClient實例
    HttpClient httpClient = new HttpClient();
    // 設置http連接主機服務超時時間:15000毫秒
    // 先獲取連接管理器對象,再獲取參數對象,再進行參數的賦值
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 創建一個Get方法實例對象
    GetMethod getMethod = new GetMethod(url);
    // 設置get請求超時爲60000毫秒
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    // 設置請求重試機制,默認重試次數:3次,參數設置爲true,重試機制可用,false相反
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
    try {
      // 執行Get方法
      int statusCode = httpClient.executeMethod(getMethod);
      // 判斷返回碼
      if (statusCode != HttpStatus.SC_OK) {
        // 如果狀態碼返回的不是ok,說明失敗了,打印錯誤信息
        System.err.println("Method faild: " + getMethod.getStatusLine());
      } else {
        // 通過getMethod實例,獲取遠程的一個輸入流
        is = getMethod.getResponseBodyAsStream();
        // 包裝輸入流
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuffer sbf = new StringBuffer();
        // 讀取封裝的輸入流
        String temp = null;
        while ((temp = br.readLine()) != null) {
          sbf.append(temp).append("\r\n");
        }

        result = sbf.toString();
      }

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 關閉資源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 釋放連接
      getMethod.releaseConnection();
    }
    return result;
  }

  public static String doPost(String url, Map<String, Object> paramMap) {
    // 獲取輸入流
    InputStream is = null;
    BufferedReader br = null;
    String result = null;
    // 創建httpClient實例對象
    HttpClient httpClient = new HttpClient();
    // 設置httpClient連接主機服務器超時時間:15000毫秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 創建post請求方法實例對象
    PostMethod postMethod = new PostMethod(url);
    // 設置post請求超時時間
    postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);

    NameValuePair[] nvp = null;
    // 判斷參數map集合paramMap是否爲空
    if (null != paramMap && paramMap.size() > 0) {// 不爲空
      // 創建鍵值參數對象數組,大小爲參數的個數
      nvp = new NameValuePair[paramMap.size()];
      // 循環遍歷參數集合map
      Set<Entry<String, Object>> entrySet = paramMap.entrySet();
      // 獲取迭代器
      Iterator<Entry<String, Object>> iterator = entrySet.iterator();

      int index = 0;
      while (iterator.hasNext()) {
        Entry<String, Object> mapEntry = iterator.next();
        // 從mapEntry中獲取key和value創建鍵值對象存放到數組中
        try {
          nvp[index] = new NameValuePair(mapEntry.getKey(),
              new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        index++;
      }
    }
    // 判斷nvp數組是否爲空
    if (null != nvp && nvp.length > 0) {
      // 將參數存放到requestBody對象中
      postMethod.setRequestBody(nvp);
    }
    // 執行POST方法
    try {
      int statusCode = httpClient.executeMethod(postMethod);
      // 判斷是否成功
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method faild: " + postMethod.getStatusLine());
      }
      // 獲取遠程返回的數據
      is = postMethod.getResponseBodyAsStream();
      // 封裝輸入流
      br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

      StringBuffer sbf = new StringBuffer();
      String temp = null;
      while ((temp = br.readLine()) != null) {
        sbf.append(temp).append("\r\n");
      }

      result = sbf.toString();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 關閉資源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 釋放連接
      postMethod.releaseConnection();
    }
    return result;
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章