PHP CURL and java http

  • 2021-09-11 19:37:32
  • OfStack

php curl

Sometimes our projects need to interact with the third-party platform. For example.

Now there are two platforms, A and B. Party A realized one part of key business (such as user information, etc.) by A in the first one period. Then, based on one part of the reason, there are now one business that needs B to realize, and the implementation program calls one sensitive interface that can only run on the B server, so it can only interact between the two platforms. curl is the solution to this problem.

curl is an php extension that you can view as a compact browser that can access other Web sites.
To use curl, you have to open the relevant configuration in php. ini to use it.
Commonly used data formats for interaction between platforms are json, xml and other popular data formats.


<?php
 @param
 $url   Interface address 
 $https  Whether it is 1 A Https  Request 
 $post  Whether it is post  Request 
 $post_data post  Submit data   Array format 
function curlHttp($url,$https = false,$post = false,$post_data = array())
{
  $ch = curl_init();                            // Initialization 1 A curl
  curl_setopt($ch, CURLOPT_URL,$url);     // Setting interface address   Such as: http://wwww.xxxx.co/api.php
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);// Whether to put CRUL To assign the contents of the obtained to a variable 
  curl_setopt($ch,CURLOPT_HEADER,0);// Whether a response header is required 
  /* Whether or not post Submit data */
  if($post){
    curl_setopt($ch,CURLOPT_POST,1);
    if(!empty($post_data)){
      curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
    }
  }
  /* Do you need a security certificate */
  if($https)
  {
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  // https Request   Do not verify certificates and hosts
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  }
  $output = curl_exec($ch);
  curl_close($ch);
  return $output;
}
?> 

Now the interface address http://www.xxxxx.com/api/{sid} can return one json data format of user through get mode, so how can we obtain the data of the third party platform


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

Where $user is to get user array information.
Here, the curl simulation browser makes an 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 the object name is long enough not easy to remember. Everything else is good, and it is first compiled into bytecode and then run by java virtual machine, unlike php, which needs to be compiled once every time and then run.
Realization of php curl by java

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 
{
  /**
   *  To the specified URL Send GET Request for the method 
   * 
   * @param url
   *       Sending the requested URL
   * @param param
   *       Request parameter, which should be  name1=value1&name2=value2  The form of. 
   * @return String  The response result of the remote resource represented by 
   */
  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);
      //  Open and URL Connection between 
      URLConnection connection = realUrl.openConnection();
      //  Setting Common Request Properties 
      connection.setRequestProperty("accept", "*/*");
      connection.setRequestProperty("connection","close");
      connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

      //  Establish an actual connection 
      connection.connect();

      /*
      //  Get all response header fields 
      Map<String, List<String>> map = connection.getHeaderFields();
      //  Traverse all response header fields 
      for (String key : map.keySet())
      {
        System.out.println(key + "--->" + map.get(key));
      }
      */

      //  Definition  BufferedReader Input stream to read URL Response of 
      in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

      String line;

      while ((line = in.readLine()) != null)
      {
        result += line;
      }
    } catch (Exception e) {
      System.out.println(" Send GET Exception in request! " + e);
      e.printStackTrace();
    }
    //  Use finally Block to close the input stream 
    finally {
      try {
        if (in != null) {
          in.close();
        }
      } catch (Exception e2) {
        e2.printStackTrace();
      }
    }
    return result.equals("") ? null : result;
  }

  /**
   *  To the specified  URL  Send POST Request for the method 
   * 
   * @param url
   *       Sending the requested  URL
   * @param param
   *       Request parameter, which should be  name1=value1&name2=value2  The form of. 
   * @return String  The response result of the remote resource represented by 
   */
  public static String post(String url, String param) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
      URL realUrl = new URL(url);
      //  Open and URL Connection between 
      URLConnection conn = realUrl.openConnection();
      //  Setting Common Request Properties 
      conn.setRequestProperty("accept", "*/*");
      conn.setRequestProperty("connection", "Keep-Alive");
      conn.setRequestProperty("user-agent",
          "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
      //  Send POST The request must be set with the following two lines 
      conn.setDoOutput(true);
      conn.setDoInput(true);
      //  Get URLConnection The output stream corresponding to the object 
      out = new PrintWriter(conn.getOutputStream());
      //  Send request parameters 
      out.print(param);
      // flush Buffering of output stream 
      out.flush();
      //  Definition BufferedReader Input stream to read URL Response of 
      in = new BufferedReader(
          new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        result += line;
      }
    } catch (Exception e) {
      System.out.println(" Send  POST  Exception in request! "+e);
      e.printStackTrace();
    }
    // Use finally Block to close the output stream, the input stream 
    finally{
      try{
        if(out!=null){
          out.close();
        }
        if(in!=null){
          in.close();
        }
      }
      catch(IOException ex){
        ex.printStackTrace();
      }
    }
    return result;
  }  
}

Then the use of php 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);   // Start simulating browser requests 
        JSONObject json = JSONObject.fromObject(data);  // Parse the returned json Data results 

  }
}

Related articles: