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);
        }


你可能感兴趣的:(java,http,模拟)