PHP CURL and java http usage steps analysis

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

This time I will bring you the step-by-step analysis of using PHP CURL and java http. What are theprecautionsfor 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.

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

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 completelyobject-orientedlanguage. 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> 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
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!