连接http接口方法

来源:互联网 发布:informix批量生成数据 编辑:程序博客网 时间:2024/05/17 22:30
/**
  * http连接方法
  *
  * @param commString
  * @param address
  * @return
  */
 public String connectURL(String commString, String address) {
  String rec_string = "";
  URL url = null;
  HttpURLConnection urlConn = null;
  try {
   url = new URL(address);
   // 打开连接
   urlConn = (HttpURLConnection) url.openConnection();
   // 连接主机的超时时间(单位:毫秒)
   urlConn.setConnectTimeout(30000);
   // 从主机读取数据的超时时间(单位:毫秒)
   urlConn.setReadTimeout(30000);
   // 设定请求的方法为"POST",默认是GET
   urlConn.setRequestMethod("POST");
   // http正文内,因此需要设为true, 默认情况下是false;
   urlConn.setDoOutput(true);
   // 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,
   OutputStream out = urlConn.getOutputStream();
   out.write(commString.getBytes("UTF-8"));
   out.flush();
   out.close();
   // 读取接口的返回的流
   BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
   StringBuffer sb = new StringBuffer();
   int ch;
   while ((ch = rd.read()) > -1) {
    sb.append((char) ch);
   }
   rec_string = sb.toString().trim();
   rd.close();
  } catch (Exception e) {
   log.error(e);
  } finally {
   if (urlConn != null) {
    urlConn.disconnect();
   }
  }
  return rec_string;
 }
原创粉丝点击