java模擬http發送請求與接受返回數據

String result = "";
        
        // 定義http客戶端對象--httpClient
        HttpClient httpClient = new HttpClient();
         
        // 定義並實例化客戶端鏈接對象-postMethod
        PostMethod postMethod = new PostMethod("spacer.gifhttp://apis.i-comm.cn:8080/KSO/reg_member2/");
         
        try{
         // 設置http的頭
//          postMethod.setRequestHeader("ContentType",
//            "application/x-www-form-urlencoded;charset=UTF-8");
       
         // 填入各個表單域的值
            NameValuePair um  = new NameValuePair("username", username);
            NameValuePair am= new NameValuePair("acct_nm", acct_nm);
            NameValuePair arm = new NameValuePair("acct_real_nm", real_nm);
            NameValuePair pn= new NameValuePair("phoneNumber", phone_number);
            NameValuePair pd = new NameValuePair("password", MD5Util.MD5(pwd));

            NameValuePair[] data = { um,am,arm,pn,pd };

         
         // 將表單的值放入postMethod中
         postMethod.setRequestBody(data);
       
         // 定義訪問地址的鏈接狀態
         int statusCode = 0;
         try {
          // 客戶端請求url數據
          statusCode = httpClient.executeMethod(postMethod);
         } catch (Exception e) {
          e.printStackTrace();
          jsonMessage.put("msgcode", "-1");
         }
         
         // 請求成功狀態-200
         if (statusCode == HttpStatus.SC_OK) {
          try {
           result = postMethod.getResponseBodyAsString();
           if(result.equals("1")){
jsonMessage.put("openid", openId);
jsonMessage.put("msgcode", "0");
           }
           else{
            jsonMessage.put("msgcode", "-1");
           }
          } catch (IOException e) {
           e.printStackTrace();
           jsonMessage.put("msgcode", "-1");
          }
         }
        } catch (Exception e) {
         jsonMessage.put("msgcode", "-1");
        } finally {
         // 釋放鏈接
         postMethod.releaseConnection();
         httpClient.getHttpConnectionManager().closeIdleConnections(0);
        }


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