PHP CURL与java http使用方法详解

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP CURL与java http使用方法详解脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

php curl

有时候我们的项目需要与第三方平台进行交互。举个例子。

现在有A、B两个平台。 甲方在最初一段时间由A实现了一部分关键业务(如用户信息等)。 然后基于一部分原因,现在有一些业务需要B来实现,且实现程序调用了一些敏感的接口只能在B方服务器上跑,那么只能做两个平台之间的交互了。curl 就是这种问题的解决方案

curl 是一个PHP扩展,你可以看作一个可以访问其他网站的精简版浏览器。
要使用curl 你得在Php.ini 中开启相关的配置才能使用。
常用的平台之间交互的数据格式 有json、XMl等比较流行的数据格式。

<&#63;php
 @param
 $url  接口地址
 $https 是否是一个Https 请求
 $post 是否是post 请求
 $post_data post 提交数据 数组格式
function curlHttp($url,$https = false,$post = false,$post_data = array())
{
  $ch = curl_init();                            //初始化一个curl
  curl_setopt($ch, CURLOPT_URL,$url);     //设置接口地址 如:http://wwww.xxxx.co/api.php
  curl_setopt($ch, CURLOPT_RETURNtransfer,1);//是否把CRUL获取的内容赋值到变量
  curl_setopt($ch,CURLOPT_HEADER,0);//是否需要响应头
  /*是否post提交数据*/
  if($post){
    curl_setopt($ch,CURLOPT_POST,1);
    if(!empty($post_data)){
      curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
    }
  }
  /*是否需要安全证书*/
  if($https)
  {
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  // https请求 不验证证书和hosts
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  }
  $output = curl_exec($ch);
  curl_close($ch);
  return $output;
}
?> 

现在 接口地址 http://www.xxxxx.COM/api/{sid} 这个接口地址通过get 方式可以返回一个user 的 json数据格式 ,那么我们怎么去获取第三方平台的数据

<?php
    $sid = 1;
    $url = "http://www.xxxxx.com/api/{$sid}";
    $data = curlHttp($url);
  $user = json_decode($data,true); 
?>

其中$user就是获取user数组信息。
在这里 curl 模拟浏览器对该域名进行了get请求(当然,根据我们在参数中的设置,我们也可以去模拟post https 等请求),获取到了响应的数据。

java http 实现了类似php curl 的功能

java 是一门完全面向对象的语言,我觉得除了对象名够长不容易记忆外。其它的都很好,且它是先编译成字节码然后由java虚拟机去运行的,不像 php 每次都需要去编译一次以后采取运行。
java对php curl 的实现

文件 tool.HttPRequest

package tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWrITer;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import java.net.URLEncoder;

import LOG.Log;

public class HttpRequest 
{
  /**
   * 向指定URL发送GET方法的请求
   * 
   * @param url
   *      发送请求的URL
   * @param param
   *      请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
   * @return String 所代表远程资的响应结果
   */
  public static String get(String url,String param)
  {
    String result = "";
    BufferedReader in = null;
    try {
      String urlnamestring = null;

      if(param == null)
        urlNameString = url;
      else
        urlNameString = url + "?" + param;

      //System.out.println("curl http url : " + urlNameString);

      URL realUrl = new URL(urlNameString);
      // 打开和URL之间的连接
      URLConnection connection = realUrl.openConnection();
      // 设置通用的请求属性
      connection.setRequestProperty("accept", "*/*");
      connection.setRequestProperty("connection","close");
      connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

      // 建立实际的连接
      connection.connect();

      /*
      // 获取所有响应头字段
      Map<String, List<String>> map = connection.getHeaderFields();
      // 遍历所有的响应头字段
      for (String key : map.keySet())
      {
        System.out.println(key + "--->" + map.get(key));
      }
      */

      // 定义 BufferedReader输入流来读取URL的响应
      in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

      String line;

      while ((line = in.readLine()) != null)
      {
        result += line;
      }
    } catch (Exception e) {
      System.out.println("发送GET请求出现异常!" + e);
      e.printStackTrace();
    }
    // 使用finally块来关闭输入流
    finally {
      try {
        if (in != null) {
          in.close();
        }
      } catch (Exception e2) {
        e2.printStackTrace();
      }
    }
    return result.equals("") ? null : result;
  }

  /**
   * 向指定 URL 发送POST方法的请求
   * 
   * @param url
   *      发送请求的 URL
   * @param param
   *      请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
   * @return String 所代表远程资源的响应结果
   */
  public static String post(String url, String param) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
      URL realUrl = new URL(url);
      // 打开和URL之间的连接
      URLConnection conn = realUrl.openConnection();
      // 设置通用的请求属性
      conn.setRequestProperty("accept", "*/*");
      conn.setRequestProperty("connection", "Keep-Alive");
      conn.setRequestProperty("user-agent",
          "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
      // 发送POST请求必须设置如下两行
      conn.setDoOutput(true);
      conn.setDoInput(true);
      // 获取URLConnection对象对应的输出流
      out = new PrintWriter(conn.getOutputStream());
      // 发送请求参数
      out.print(param);
      // flush输出流的缓冲
      out.flush();
      // 定义BufferedReader输入流来读取URL的响应
      in = new BufferedReader(
          new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        result += line;
      }
    } catch (Exception e) {
      System.out.println("发送 POST 请求出现异常!"+e);
      e.printStackTrace();
    }
    //使用finally块来关闭输出流、输入流
    finally{
      try{
        if(out!=null){
          out.close();
        }
        if(in!=null){
          in.close();
        }
      }
      catch(IOException ex){
        ex.printStackTrace();
      }
    }
    return result;
  }  
}

然后类似php的使用如下

web.app.controller.IndexController

package web.app.controller;

import tool.HttpRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("Index")
public class IndexController
{
    @RequestMapping(value="index",method={RequestMethod.GET,RequestMethod.POST},produces="text/htML;charset=utf-8")
     @ResponseBody
  public String index()
  {
    String sid = "1";
    String apiUrl = "http://www.xxxxx.com/api/" +sid;
        String data = HttpRequest.get(apiUrl,null);   //开始模拟浏览器请求
        JSONObject JSON = JSONObject.FromObject(data);  //解析返回的json数据结果

  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本宝典。

脚本宝典总结

以上是脚本宝典为你收集整理的PHP CURL与java http使用方法详解全部内容,希望文章能够帮你解决PHP CURL与java http使用方法详解所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:java