[Java] 兩種發起POST請求方法,並接收返回的響應內容的處理方式


1、利用apache提供的commons-httpclient-3.0.jar包

代碼如下:

/**
  * 利用HttpClient發起POST請求,並接收返回的響應內容
  * 
  * @param url 請求鏈接
  * @param type 交易或響應編號
  * @param message 請求內容
  * @return 響應內容
  */
  public String transRequest(String url, String type, String message) {
  // 響應內容
  String result = "";
  // 定義http客戶端對象--httpClient
  HttpClient httpClient = new HttpClient();
  // 定義並實例化客戶端鏈接對象-postMethod
  PostMethod postMethod = new PostMethod(url);
  try{
   // 設置http的頭
   postMethod.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
   // 填入各個表單域的值
   NameValuePair[] data = { new NameValuePair("type", type), new NameValuePair("message", message) };
   // 將表單的值放入postMethod中
   postMethod.setRequestBody(data);
   // 定義訪問地址的鏈接狀態
   int statusCode = 0;
   try
 
{ // 客戶端請求url數據 statusCode = httpClient.executeMethod(postMethod); }
catch (Exception e)
  { e.printStackTrace(); }
// 請求成功狀態-200 if (statusCode == HttpStatus.SC_OK) { try { result = postMethod.getResponseBodyAsString(); } catch (IOException e) { e.printStackTrace(); } } else { log.error("請求返回狀態:" + statusCode); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { // 釋放鏈接 postMethod.releaseConnection(); httpClient.getHttpConnectionManager().closeIdleConnections(0); } return result; }

 

 

2、利用java自帶的java.net.*包下提供的工具類

代碼如下:

/**
  * 利用URL發起POST請求,並接收返回信息
  * 
  * @param url 請求URL
  * @param message 請求參數
  * @return 響應內容
  */
 @Override
 public String transport(String url, String message)
{   StringBuffer sb
= new StringBuffer();   try
  {     URL urls = new URL(url);     HttpURLConnection uc = (HttpURLConnection) urls.openConnection();     uc.setRequestMethod("POST");     uc.setRequestProperty("content-type", "application/x-www-form-urlencoded");     uc.setRequestProperty("charset", "UTF-8");     uc.setDoOutput(true);     uc.setDoInput(true);     uc.setReadTimeout(10000);     uc.setConnectTimeout(10000);
    OutputStream os
= uc.getOutputStream();     DataOutputStream dos = new DataOutputStream(os);     dos.write(message.getBytes("utf-8"));     dos.flush();     os.close();
    BufferedReader in
= new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));     String readLine = "";     while ((readLine = in.readLine()) != null)
    {
      sb.append(readLine);     }     in.close();     }
    catch (Exception e)
    {       log.error(e.getMessage(), e);     }
    return sb.toString(); }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM