Php curl and java http Usage Details, curljava
Php curl
Sometimes our project needs to interact with a third-party platform. For example.
There are now two platforms, A and B. At the beginning, Party A implemented some key services (such as user information) by Party ). For some reason, some services need to be implemented by B, and the implementation program calls some sensitive interfaces that can only be run on B's server, therefore, only two platforms can interact with each other. Curl is the solution to this problem.
Curl is a php extension. You can see it as a simplified browser that can access other websites.
To use curl, you must enable the relevant configuration in php. ini.
Commonly used data formats for interaction between platforms include json, xml, and other popular data formats.
<? Php @ param $ url interface address $ whether https is an Https request $ whether post is a post request $ post_data post submit data array format function curlHttp ($ url, $ https = false, $ post = false, $ post_data = array () {$ ch = curl_init (); // initialize a curl curl_setopt ($ ch, CURLOPT_URL, $ url ); // set the interface address such as: http://wwww.xxxx.co/api.php curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); // whether to assign the content obtained by CRUL to the variable curl_setopt ($ ch, CURLOPT_HEADER, 0 ); // whether the response header is required/* Whether to post the submitted data */if ($ post) {cur Rochelle setopt ($ ch, CURLOPT_POST, 1); if (! Empty ($ post_data) {curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post_data) ;}/ * whether a security certificate is required */if ($ https) {curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https requests do not verify the certificate and hosts curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, FALSE);} $ output = curl_exec ($ ch); curl_close ($ ch ); return $ output ;}?>
The current interface address is http://www.xxxxx.com/api/javassid}. This interface address can return the json data format of a user through the get method. How can we obtain data from a third-party platform?
<?php $sid = 1; $url = "http://www.xxxxx.com/api/{$sid}"; $data = curlHttp($url); $user = json_decode($data,true); ?>
$ User is used to obtain the user array information.
Here, curl simulates the browser to make a get request for the domain name (of course, based on our settings in the parameter, we can also simulate post https and other requests) and get the response data.
Java http implements functions similar to php curl
Java is a fully object-oriented language. I think it is not easy to remember except that the object name is long enough. Others are good, and it is first compiled into bytecode and then run by the Java Virtual Machine, unlike php every time it needs to be compiled and then run.
Java 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 {/*** request for sending a GET method to a specified URL ** @ param url * The request URL * @ param * request parameter, the request parameters should be in the form of name1 = value1 & name2 = value2. * @ Return String indicates the response result of the Remote resource */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); // enable the URL connection URLConnection connection = realUrl. openConnection (); // set the common request attribute connection. setRequestProperty ("accept", "*/*"); connection. setRequestProperty ("connection", "close"); connection. setRequestProperty ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); // create an actual connection Connection. connect (); // * // obtain all response header fields Map <String, List <String> map = connection. getHeaderFields (); // traverses all response header fields for (String key: map. keySet () {System. out. println (key + "--->" + map. get (key);} * // defines the BufferedReader input stream to read the URL response in = new BufferedReader (new InputStreamReader (connection. getInputStream (); String line; while (line = in. readLine ())! = Null) {result + = line;} catch (Exception e) {System. out. println ("an Exception occurred when sending a GET request! "+ E); e. printStackTrace () ;}// use the finally block to close the input stream finally {try {if (in! = Null) {in. close () ;}} catch (Exception e2) {e2.printStackTrace () ;}} return result. equals ("")? Null: result;}/*** send a POST method request to a specified URL ** @ param url * The request URL * @ param * request parameter, the request parameters should be in the form of name1 = value1 & name2 = value2. * @ Return String indicates the response result of the Remote resource */public static String post (String url, String param) {PrintWriter out = null; BufferedReader in = null; string result = ""; try {URL realUrl = new URL (url); // enable the URL Connection URLConnection conn = realUrl. openConnection (); // set the common request attribute conn. setRequestProperty ("accept", "*/*"); conn. setRequestProperty ("connection", "Keep-Alive"); conn. setRequestProperty ("user-agent "," Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) "); // The following two rows of conn must be set to send a POST request. setDoOutput (true); conn. setDoInput (true); // get the output stream of the URLConnection object out = new PrintWriter (conn. getOutputStream (); // sends the request parameter out. print (param); // flush the Buffer out of the output stream. flush (); // defines the BufferedReader input stream to read the URL response in = new BufferedReader (new InputStreamReader (conn. getInputStream (); String line; while (line = in. readLine () )! = Null) {result + = line;} catch (Exception e) {System. out. println ("an Exception occurred when sending the POST request! "+ E); e. printStackTrace () ;}// use finally blocks to close the output stream and input stream finally {try {if (out! = Null) {out. close () ;}if (in! = Null) {in. close () ;}catch (IOException ex) {ex. printStackTrace () ;}} return result ;}}
The usage 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 to simulate a browser request for JSONObject json = JSONObject. fromObject (data); // parse the returned json data result }}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.