HttpURLConnection post method

 public String getServerString(URL url,String Data)
    {      
         StringBuffer SnapShotResponse = new StringBuffer("");
         String SnapShotString = "";
         BufferedReader br;
        try {
              HttpURLConnection connection = (HttpURLConnection)url.openConnection();

              connection.setDoInput(true);
              connection.setDoOutput(true);
              connection.setUseCaches(false);
              connection.setRequestMethod("POST");
              //connection.setRequestProperty("Content-Type", "application/xml; charset=Big5");
              connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
             
              connection.setRequestProperty("Content-Length", "" +Integer.toString(Data.getBytes().length));
              connection.setInstanceFollowRedirects(true);
              connection.setConnectTimeout(8000);

              DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
              wr.write(Data.getBytes());
              wr.flush();
              wr.close();
      
            
              br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
              String line;
              while((line=br.readLine())!=null){
               SnapShotResponse.append(line);
              }

              SnapShotString = SnapShotResponse.toString();
              connection.disconnect();
              br.close();

            } catch (Exception e)
            {
              SnapShotString = errCode;
            }finally {
              br = null;
            }

          return SnapShotString;
    }

posted on 2011-07-11 16:02  hinslam  阅读(395)  评论(0编辑  收藏  举报

导航