error8311 发表于 2013-1-28 19:07:42

HttpURLConnection 访问

/**
  * HttpURLConnection 访问 
  * @param xml
  *             入参
  * @param ur
  *             访问UEL地址
  */
 public String synstatus(String xml, String ur)
 {
  HttpURLConnection httpConn = null;
  OutputStream os = null;
  OutputStreamWriter osw = null;
  Integer result = -1;
  try
  {
   // 调用163上的接口
   URL url = new URL (ur);
   httpConn = (HttpURLConnection) url.openConnection ();
   HttpURLConnection.setFollowRedirects (true);
   httpConn.setDoOutput (true);
   httpConn.setRequestMethod ("POST");
   httpConn.setRequestProperty ("Content-Type","text/xml");
   httpConn.connect ();
   // 设置连接超时时间
   httpConn.setConnectTimeout (5000);
   // 设置读取超时时间
   httpConn.setReadTimeout (5000);
   os = httpConn.getOutputStream ();
   osw = new OutputStreamWriter (os);
   osw.write (xml.toCharArray (),0,xml.length ());
   osw.flush ();
   // 读取响应数据
   int code = httpConn.getResponseCode ();
   // 存放响应结果
   String sTotalString = "";
   System.out.println ("code::" + code);
   // 是否正常响应
   if(code == 200)
   {
    
    String sCurrentLine = "";
    // 读取响应数据
    InputStream is = httpConn.getInputStream ();
    BufferedReader reader = new BufferedReader (
     new InputStreamReader (is));
    while ((sCurrentLine = reader.readLine ()) != null)
    {
     if(sCurrentLine.length () > 0)
     {
      sTotalString = sTotalString
       + sCurrentLine.trim ();
     }
    }
         return sTotalString ;
   }
   else
   {
    sTotalString = "远程服务器连接失败,错误代码:" + code;
   }
  }catch (Exception e)
  {
   System.out.println (e.getMessage ());
  }
  finally
  {
   try
   {
    // 关闭流
    if(osw != null && os != null)
    {
     
     osw.close ();
     os.close ();
    }
   }catch (IOException e)
   {
    e.printStackTrace ();
   }
   // 断开连接
   httpConn.disconnect ();
  }
  return sTotalString ;
  
 }
页: [1]
查看完整版本: HttpURLConnection 访问