>  기사  >  백엔드 개발  >  PHP CURL 및 Java http 사용 방법에 대한 자세한 설명

PHP CURL 및 Java http 사용 방법에 대한 자세한 설명

jacklove
jacklove원래의
2018-06-29 17:25:461496검색

이 기사에서는 주로 PHP CURL 및 Java http의 사용법을 자세히 소개하며, 관심 있는 친구는 이를 참조할 수 있습니다.

php 컬

때때로 우리 프로젝트는 타사 플랫폼과 상호 작용해야 합니다. 예를 들어보세요.

이제 플랫폼 A와 B 두 개가 있습니다. 초기에 당사자 A는 몇 가지 핵심 업무(사용자 정보 등)를 수행했습니다. 그러면 어떤 이유로 B 측에서 구현해야 하는 일부 비즈니스가 있고 구현 프로그램은 B 측 서버에서만 실행할 수 있는 일부 민감한 인터페이스를 호출하므로 두 플랫폼 간의 상호 작용만 이루어질 수 있습니다. 컬은 이 문제에 대한 해결책이다.

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 메소드를 통해 사용자의 json 데이터 형식을 반환할 수 있으므로 어떻게 가져오나요? 타사 플랫폼 $user가 사용자 배열 정보를 얻는 데이터

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

입니다.
여기서 컬은 브라우저를 시뮬레이션하여 도메인 이름에 대한 가져오기 요청을 만들고(물론 매개변수의 설정에 따라 게시 https 및 기타 요청을 시뮬레이션할 수도 있음) 응답 데이터를 얻습니다.

java http는 php 컬과 유사한 기능을 구현합니다.

java는 완전히 객체 지향적인 언어입니다. 객체 이름이 충분히 길고 기억하기 어려울 것 같습니다. 다른 모든 것은 괜찮습니다. 매번 컴파일하고 실행해야 하는 PHP와 달리 먼저 바이트코드로 컴파일된 다음 Java 가상 머신에 의해 실행됩니다.
Java의 PHP 컬 구현

File 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 WeChat 개발 WeChat에서 영구 저장 장치로 임시 전환을 기록합니다 php 기술

PHP 디자인 패턴 등록 트리 패턴 분석 php 기술

win10 Apache 구성 가상 솔루션 호스트 PHP 트릭 후 로컬 호스트가 작동하지 않습니다

위 내용은 PHP CURL 및 Java http 사용 방법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.