当前位置: 移动技术网 > IT编程>开发语言>Java > java发送http get请求的两种方法(总结)

java发送http get请求的两种方法(总结)

2019年07月22日  | 移动技术网IT编程  | 我要评论

长话短说,废话不说

一、第一种方式,通过httpclient方式,代码如下:

public static string httpget(string url, string charset)
   throws httpexception, ioexception {
  string json = null;
  httpget httpget = new httpget();
  // 设置参数
  try {
   httpget.seturi(new uri(url));
  } catch (urisyntaxexception e) {
   throw new httpexception("请求url格式错误。"+e.getmessage());
  }
  // 发送请求
  httpresponse httpresponse = client.execute(httpget);
  // 获取返回的数据
  httpentity entity = httpresponse.getentity();
  byte[] body = entityutils.tobytearray(entity);
  statusline sl = httpresponse.getstatusline();
  int statuscode = sl.getstatuscode();
  if (statuscode == 200) {
   json = new string(body, charset);
   entity.consumecontent();
  } else {
   throw new httpexception("statuscode="+statuscode);
  }
  return json;
}

二、第二种方式,通过流的形式,贴代码:

/**
  * 发送http get请求
  * 
  * @param geturl
  * @return
  */
  public string sendgetrequest(string geturl)
  {
   stringbuffer sb = new stringbuffer();
   inputstreamreader isr = null;
   bufferedreader br = null;
   try
   {
     url url = new url(geturl);
     urlconnection urlconnection = url.openconnection();
     urlconnection.setallowuserinteraction(false);
     isr = new inputstreamreader(url.openstream());
     br = new bufferedreader(isr);
     string line;
     while ((line = br.readline()) != null)
     {
      sb.append(line);
     }
   }
   catch (ioexception e)
   {
     e.printstacktrace();
   }
   finally
   {
     fileoperator.closeresources(isr, br);
   }
   return sb.tostring();
  }
}

这两种实现方式不同,怎么使用看个人喜好吧,不过我在项目开发过程中,使用流的方式部署在预发机(linux机器)上会出现返回null的情况,但是本地windows却正常访问,而且,换另外一台预发机也能正常获取数据,目前还没有研究出个所以然。。。

以上这篇java发送http get请求的两种方法(总结)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网