六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 44|回复: 0

HttpURLConnection 访问

[复制链接]

升级  30%

3

主题

3

主题

3

主题

童生

Rank: 1

积分
15
 楼主| 发表于 2013-1-15 02:42:25 | 显示全部楼层 |阅读模式
/**
  * 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 ;
  
 }
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表