PHP Curl and Java HTTP usage steps parsing

Source: Internet
Author: User
Tags finally block
This time for everyone to bring PHP curl and Java HTTP use steps to resolve, PHP curl and Java HTTP Use of considerations, the following is the actual case, take a look.

PHP Curl

Sometimes our projects need to interact with third-party platforms. Let me give you an example.

There are now a, b two platforms. During the initial period, party a realizes part of the key business (such as user information, etc.) by a. Then, for some reason, there are some businesses that need B to implement, and the implementation program calls some sensitive interfaces to run on the B-party server only, then it can only do two platform interactions. Curl is the solution to this problem.

Curl is a php extension that you can view as a lite browser that can access other websites.
To use curl you have to turn on the relevant configuration in php.ini to use it.
The data format of the interaction between the common platforms has JSON, XML and other popular data formats.

<?php @param $url interface Address $https Whether it is an HTTPS request $post is a POST request $post _data post submission data                            Array Format function curlhttp ($url, $https = False, $post = False, $post _data = Array ()) {$ch = Curl_init ();     Initializes 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 Crul acquired content to the variable curl_setopt (    $ch, curlopt_header,0);//Whether you need to respond to header/* If post data is submitted */if ($post) {curl_setopt ($ch, curlopt_post,1);    if (!empty ($post _data)) {curl_setopt ($ch, Curlopt_postfields, $post _data);  }}/* Need security Certificate */if ($HTTPS) {curl_setopt ($ch, Curlopt_ssl_verifypeer, FALSE);  The HTTPS request does not validate the certificate and the hosts curl_setopt ($ch, Curlopt_ssl_verifyhost, FALSE);  } $output = Curl_exec ($ch);  Curl_close ($ch); return $output;}? 

Now interface address Http://www.xxxxx.com/api/{sid} This interface address can return a user's JSON data format via get, so how do we get data from third-party platforms?

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

Where $user is to get the user array information.
Here the Curl Simulation browser makes a GET request for the domain name (of course, according to our settings in the parameters, we can also simulate the post HTTPS request), get the response data.

Java HTTP implements PHP-like Curl functionality

Java is a completely object-oriented language, I think in addition to the object name is long enough not easy to remember. The rest is good, and it is compiled into bytecode and then run by the Java Virtual machine, unlike PHP, which needs to be compiled once a time to run.
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 {/** * a request to send a GET method to a specified URL * * @param URL *   The URL of the sending request * @param param * Request parameter, the request parameter should be in the form of name1=value1&name2=value2.    * @return The response result of the remote resource represented by 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);      The connection between open and URL urlconnection connection = Realurl.openconnection ();      Set the generic 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) ");      Establish the actual connection connection.connect ();      /*//Get all response header fields Map<string, list<string>> Map = Connection.getheaderfields ();      Traverse all the response header fields for (String Key:map.keySet ()) {System.out.println (key + "--->" + map.get (key)); } *///define BufferedReader input stream to read the response of the URL in = new BufferedReader (New InputStreamReader (connection.getinputstr      EAM ()));      String Line;      while (line = In.readline ()) = null) {result + = line; }} catch (Exception e) {System.out.println ("Send GET request exception!)      "+ 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; /** * Request to send a POST method to the specified URL *   * @param URL * Send request URL * @param param * Request parameter, request parameter should be in the form of name1=value1&name2=value2.    * @return The response result of the remote resource represented by String */public static string post (string url, string param) {printwriter out = null;    BufferedReader in = null;    String result = "";      try {URL realurl = new URL (URL);      The connection between open and URL URLConnection conn = realurl.openconnection ();      Set the generic 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 Send POST request must be set to the following two lines conn.setdooutput (true);      Conn.setdoinput (TRUE);      Gets the output stream corresponding to the URLConnection object out = new PrintWriter (Conn.getoutputstream ());      Send request parameter out.print (param);      Flush output Stream Buffer Out.flush ();      Defines the BufferedReader input stream to read the response of the URL in = new BufferedReader (New InputStreamReader (Conn.getinputstream ())); StRing Line;      while (line = In.readline ()) = null) {result + = line; }} catch (Exception e) {System.out.println ("send POST request exception!      "+e);    E.printstacktrace ();        }//Use the finally block to close the output stream, input stream finally{try{if (out!=null) {out.close ();        } if (In!=null) {in.close ();      }} catch (IOException ex) {ex.printstacktrace ();  }} return result; }  }

Then use PHP like the following

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 request        jsonobject JSON = jsonobject.fromobject (data);  Parse the returned JSON data result  }}

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

PHP implementation of multivariate linear regression simulation curve algorithm steps

PHP Delete a one-dimensional array of value elements steps in detail

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.