网络编程 
首页 > 网络编程 > 浏览文章

PHP CURL与java http使用方法详解

(编辑:jimmy 日期: 2024/5/20 浏览:3 次 )

php curl

有时候我们的项目需要与第三方平台进行交互。举个例子。

现在有A、B两个平台。 甲方在最初一段时间由A实现了一部分关键业务(如用户信息等)。 然后基于一部分原因,现在有一些业务需要B来实现,且实现程序调用了一些敏感的接口只能在B方服务器上跑,那么只能做两个平台之间的交互了。curl 就是这种问题的解决方案。

curl 是一个php扩展,你可以看作一个可以访问其他网站的精简版浏览器。
要使用curl 你得在php.ini 中开启相关的配置才能使用。
常用的平台之间交互的数据格式 有json、xml等比较流行的数据格式。

<"color: #3366ff">http://www.xxxxx.com/api/{sid} 这个接口地址通过get 方式可以返回一个user 的 json数据格式 ,那么我们怎么去获取第三方平台的数据

<"http://www.xxxxx.com/api/{$sid}";
    $data = curlHttp($url);
  $user = json_decode($data,true); 
"htmlcode">
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("") "";
    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;
  }  
}

然后类似php的使用如下

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数据结果

  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:PHP微信开发之微信录音临时转永久存储
下一篇:php实现mysql连接池效果实现代码