在JAVA中调用url请求,全代码,可复制

来源:互联网 发布:pc蛋蛋牛人10×0算法 编辑:程序博客网 时间:2024/05/21 01:42

最近做接口做的很烦躁,用returnUrl返回请求再调用很烦躁,找了一种在JAVA类中直接调用java请求的方法。这种方法中可以实现对接口的直接调用,还能获得返回值,对于做接口,尤其是服务端,有很重要的作用,例如,定时任务,自动定时调用接口,并处理返回来的数据。。。

public static String sendPostUrlRequest(String toUrl)
   throws ClientProtocolException, IOException {
  String interfaceData = "";

  // 获取默认的HttpClient
  HttpClient httpclient = new DefaultHttpClient();

  // 获取Get连接
  HttpGet httpGet = new HttpGet(toUrl);

  // 请求post连接
  HttpResponse response = httpclient.execute(httpGet);

  // 打印日志
  System.out.println("doGet请求状态Code:"
    + response.getStatusLine().getStatusCode());

  // 是否请求正常
  if (200 == response.getStatusLine().getStatusCode()) {

   // 获取链接返回的数据
   HttpEntity resEntity = response.getEntity();

   // 获取返回的数据流
   BufferedReader input = new BufferedReader(new InputStreamReader(
     resEntity.getContent(), "GBK"));
   String tempStr = "";

   // 获取返回的内容
   while ((tempStr = input.readLine()) != null) {
    // interfaceData += tempStr.replace("\t", "");
    interfaceData += tempStr;
   }
  }
  // 关闭连接
  httpGet.abort();
  return interfaceData;
 }

 

public static void main(String[] args) throws ClientProtocolException, IOException {
  System.out.println(""+sendPostUrlRequest("
http://tieba.baidu.com/f?kw=%C3%AB%D4%F3%B6%AB"));
 }

这里默认返回的编码字符串解析方式为GBK,有需要的可以根据需要进行选择。

原创粉丝点击