PHP CURL and java http usage steps analysis

php中世界最好的语言
Release: 2023-03-26 21:34:02
Original
1476 people have browsed it

This time I will bring you the step-by-step analysis of using PHP CURL and java http. What are the precautions for using PHP CURL and java http. The following is a practical case, let’s take a look.

php curl

Sometimes our projects need to interact with third-party platforms. for example.

Now there are two platforms A and B. In the initial period, Party A implemented some key businesses (such as user information, etc.). Then for some reasons, there are some businesses that need to be implemented by B, and the implementation program calls some sensitive interfaces and can only run on the B-side server, so the interaction between the two platforms can only be done. curl is the solution to this problem.

curl is a php extension, you can think of it as a streamlined browser that can access other websites.
To use curl, you must enable the relevant configuration in php.ini to use it.
Commonly used data formats for interaction between platforms include json, xml and other popular data formats.

<?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;
}
?>
Copy after login

Now the interface addresshttp://www.xxxxx.com/api/{sid} This interface address can return the json data format of a user through the get method, so how do we go Obtaining data from third-party platforms

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

$user is to obtain user array information.
Here, curl simulates the browser making a get request for the domain name (of course, according to our settings in the parameters, we can also simulate post https and other requests) and obtains the response data.

java http implements functions similar to php curl

java is a completely object-oriented language. I think except that the object name is long enough Not easy to remember. Everything else is fine, and it is first compiled into bytecode and then run by the Java virtual machine, unlike php which needs to be compiled and run every time.
Java's implementation of php curl

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;
  }  
}
Copy after login

Then similar php usage is as follows

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数据结果
  }
}
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps of implementing multiple linear regression simulation curve algorithm in PHP

php Delete the median value of a one-dimensional array Detailed explanation of element steps

The above is the detailed content of PHP CURL and java http usage steps analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!