JAVA HTTP請求

整理了一下經常用到的請求

1. GET

public static String sendGet(String httpUrl, Map<String, String> parameter , Map<String , String> headerMap) {
   if (parameter == null || httpUrl == null) {
      return null;
   }
   StringBuilder sb = new StringBuilder();
   Iterator<Map.Entry<String, String>> iterator = parameter.entrySet().iterator();
   while (iterator.hasNext()) {
      if (sb.length() > 0) {
         sb.append('&');
      }
      Entry<String, String> entry = iterator.next();
      String key = entry.getKey();
      sb.append(key).append('=').append(entry.getValue());
   }
   String urlStr = null;
   if (httpUrl.lastIndexOf('?') != -1) {
      urlStr = httpUrl + '&' + sb.toString();
   } else {
      urlStr = httpUrl + '?' + sb.toString();
   }
   System.out.println("-----urlStr-[" + urlStr + "]");
   HttpURLConnection httpCon = null;
   String responseBody = null;
   try {
      URL url = new URL(urlStr);
      httpCon = (HttpURLConnection) url.openConnection();
      httpCon.setDoOutput(true);
      httpCon.setRequestMethod("GET");
      httpCon.setConnectTimeout(TIME_OUT * 1000);
      httpCon.setReadTimeout(TIME_OUT * 1000);
      // 塞header
      if (headerMap != null) {
         iterator = headerMap.entrySet().iterator();
         while (iterator.hasNext()) {
            Entry<String, String> entry = iterator.next();
            httpCon.addRequestProperty(entry.getKey(), entry.getValue());
         }
      }
      // 開始讀取返回的內容
      InputStream in = null;
      if(httpCon.getResponseCode() == 400) {
         in = httpCon.getErrorStream();
      } else {
         in = httpCon.getInputStream();
      }
      byte[] readByte = new byte[1024];
      // 讀取返回的內容
      int readCount = in.read(readByte, 0, 1024);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      while (readCount != -1) {
         baos.write(readByte, 0, readCount);
         readCount = in.read(readByte, 0, 1024);
      }
      responseBody = new String(baos.toByteArray(), "UTF-8");
      baos.close();
   } catch (Exception e) {
      e.printStackTrace();
   } finally {
      if (httpCon != null)
         httpCon.disconnect();
   }
   return responseBody;
}

 

2.POST (JSON)

    header必要參數: 

  Map<String, String> headerMap = new HashMap<>(16);
  headerMap.put("Accept", "application/json");
  headerMap.put("Content-Type", "application/json;charset=utf-8");
/**
 * 使用HTTP POST JSON
 * @param httpUrl 發送的地址
 * @param postBody 發送的內容
 * @param encoding 發送的內容的編碼
 * @param headerMap 增加的Http頭信息
 * @return 返回HTTP SERVER的處理結果,如果返回null,發送失敗
 */
public static String sentPost(String httpUrl, String postBody, String encoding, Map<String, String> headerMap) {
   HttpURLConnection httpCon;
   String responseBody;
   URL url;
   try {
      url = new URL(httpUrl);
   } catch (MalformedURLException e1) {
      return null;
   }
   try {
      httpCon = (HttpURLConnection) url.openConnection();
   } catch (IOException e1) {
      return null;
   }
   if (httpCon == null) {
      return null;
   }
   httpCon.setDoOutput(true);
   httpCon.setConnectTimeout(TIME_OUT * 1000);
   httpCon.setReadTimeout(TIME_OUT * 1000);
   httpCon.setDoOutput(true);
   httpCon.setUseCaches(false);
   try {
      httpCon.setRequestMethod("POST");
   } catch (ProtocolException e1) {
      return null;
   }
   if (headerMap != null) {
      for (Entry<String, String> entry : headerMap.entrySet()) {
         httpCon.addRequestProperty(entry.getKey(), entry.getValue());
      }
   }
   if (postBody != null) {
      byte[] b = null;
      try {
         b = postBody.getBytes(encoding);
      } catch (UnsupportedEncodingException e2) {
         e2.printStackTrace();
      }
      httpCon.setFixedLengthStreamingMode(b.length);
      OutputStream output;
      try {
         output = httpCon.getOutputStream();
      } catch (IOException e1) {
         return null;
      }
      try {
         output.write(b);
      } catch (IOException e1) {
         return null;
      }
      try {
         output.flush();
         output.close();
      } catch (IOException e1) {
         return null;
      }
   }
   // 開始讀取返回的內容
   InputStream in;
   try {
      if(httpCon.getResponseCode() == 400) {
         in = httpCon.getErrorStream();
      } else {
         in = httpCon.getInputStream();
      }
   } catch (IOException e1) {
      return null;
   }
   
   int size = 0;
   try {
      size = in.available();
   } catch (IOException e1) {
      return null;
   }
   if (size == 0) {
      size = 1024;
   }
   byte[] readByte = new byte[size];
   // 讀取返回的內容
   int readCount = -1;
   try {
      readCount = in.read(readByte, 0, size);
   } catch (IOException e1) {
      return null;
   }
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   while (readCount != -1) {
      baos.write(readByte, 0, readCount);
      try {
         readCount = in.read(readByte, 0, size);
      } catch (IOException e) {
         return null;
      }
   }
   try {
      responseBody = new String(baos.toByteArray(), encoding);
   } catch (UnsupportedEncodingException e) {
      return null;
   } finally {
      httpCon.disconnect();
      try { baos.close(); } catch (IOException e) { }
   }
   return responseBody;
}

 

3.POST(form-data)

/**
 * post請求(form-data)
 */
public static String doPost(String url, Map params){

   BufferedReader in;
   try {
      // 定義HttpClient
      HttpClient client = new DefaultHttpClient();
      // 實例化HTTP方法
      HttpPost request = new HttpPost();
      request.setURI(new URI(url));

      //設置參數
      List<NameValuePair> nvpList = new ArrayList<>();
      for (Object o : params.keySet()) {
         String name = (String) o;
         String value = String.valueOf(params.get(name));
         nvpList.add(new BasicNameValuePair(name, value));
      }
      request.setEntity(new UrlEncodedFormEntity(nvpList, HTTP.UTF_8));

      HttpResponse response = client.execute(request);
      int code = response.getStatusLine().getStatusCode();
      //請求成功
      if(code == 200) {
         in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"utf-8"));
         StringBuilder sb = new StringBuilder("");
         String line;
         while ((line = in.readLine()) != null) {
            sb.append(line).append(System.getProperty("line.separator"));
         }

         in.close();

         return sb.toString();
      } else {
         return null;
      }
   } catch(Exception e) {
      e.printStackTrace();
      return null;
   }
}

 

4.POST(x-www-form-urlencoded)

/**
 * post請求(用於x-www-form-urlencoded格式的參數)
 */
public static String doPost2(String url, Map<String, String> params) {

   CloseableHttpResponse response;
   CloseableHttpClient httpClient = HttpClients.createDefault();
   HttpPost httpPost = new HttpPost(url);
   try {
      httpPost.addHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
      //參數拼接
      List<NameValuePair> nvpList = new ArrayList<>();
      if(params.size() != 0) {
          for (Object o : params.keySet()) { 
              String name = (String) o;
              String value = String.valueOf(params.get(name));
              nvpList.add(new BasicNameValuePair(name, value));
          }
      }
      httpPost.setEntity(new UrlEncodedFormEntity(nvpList, "UTF-8"));
      // 執行http請求
      response = httpClient.execute(httpPost);
      // 獲得http響應體
      HttpEntity entity = response.getEntity();
      String content = null;
      if(entity != null) {
         content = EntityUtils.toString(entity, "UTF-8");
      }
      return content;
   } catch(Exception e) {
      e.printStackTrace();
      return null;
   }
}

 

 

 

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