Beispiel #1
0
 public static String encodeURLParam(PostParameter[] _params) {
   StringBuffer ret = new StringBuffer();
   for (int i = 0; i < _params.length; i++) {
     PostParameter par = _params[i];
     ret.append(par.getName()).append("=").append(par.getValue());
     if (i + 1 < _params.length) {
       ret.append("&");
     }
   }
   return ret.toString();
 }
Beispiel #2
0
  public static String requestURL(
      String _url, String _method, PostParameter[] _headerParams, PostParameter[] _urlParams)
      throws Exception {

    if (_method.equals("GET")) {
      _url = _url + "?" + encodeURLParam(_urlParams);
    }

    URL url = new URL(_url);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    try {
      con.setDoInput(true);
      if (_method.equals("POST")) {
        con.setRequestMethod("POST");
        con.setDoOutput(true);
      }

      con.setAllowUserInteraction(false);

      if (_headerParams != null && _headerParams.length != 0) {
        for (PostParameter par : _headerParams) {
          con.setRequestProperty(par.getName(), par.getValue());
        }
      }

      if (_method.equals("POST")) {
        String t_params = encodeURLParam(_urlParams);
        byte[] bytes = t_params.getBytes("UTF-8");

        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Content-Length", Integer.toString(bytes.length));

        OutputStream t_os = con.getOutputStream();
        try {
          t_os.write(bytes);
          t_os.flush();
        } finally {
          t_os.close();
        }
      }

      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
      try {
        return in.readLine();
      } finally {
        in.close();
      }
    } finally {
      con.disconnect();
    }
  }