登录  /  注册

PHP CURL与java http使用方法的详解

jacklove
发布: 2018-06-29 17:25:46
原创
1325人浏览过

这篇文章主要为大家详细介绍了php curl与java http使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

php curl

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

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

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

<?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中文网。

您可能感兴趣的文章:

PHP微信开发之微信录音临时转永久存储php技巧

PHP设计模式之注册树模式分析php技巧

win10 apache配置虚拟主机后localhost无法使用的解决方法php技巧

以上就是PHP CURL与java http使用方法的详解的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号