PHP CURL与java http使用方法详解

网友投稿 581 2023-02-25


PHP CURL与java http使用方法详解

php curl

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

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

curl 是一个php扩展,你可以看作一个可以访问其他网站的精简版浏览器。

要使用curl 你得在php.ini 中开启相关的配置才能使用。

常用的平台之间交互的数据格式 有json、xml等比较流行的数据格式。

@param

$url 接口地址

$https 是否是一个Https 请求

$post 是否是post 请求

$post_data post 提交数据 数组格式

function curlHttp($url,$https = false,$post = false,$post_data = array())

{

$ch = curl_init(); //初始化一个curl

curl_setopt($ch, CURLOPT_URL,$url); //设置接口地址 如:http://wxxxx.co/api.php

curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//是否把CRUL获取的内容赋值到变量

curl_setopt($ch,CURLOPT_HEADER,0);//是否需要响应头

/*是否post提交数据*/

if($post){

curl_setopt($ch,CURLOPT_POST,1);

if(!empty($post_data)){

curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);

}

}

/*是否需要安全证书*/

if($https)

{

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

}

$output = curl_exec($ch);

curl_close($ch);

return $output;

}

?>

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

$sid = 1;

$url = "http://xxxxx.com/api/{$sid}";

$data = curlHttp($url);

$user = json_decode($data,true);

?>

其中$user就是获取user数组信息。

在这里 curl 模拟浏览器对该域名进行了get请求(当然,根据我们在参数中的设置,我们也可以去模拟post https 等请求),获取到了响应的数据。

java http 实现了类似php curl 的功能

java 是一门完全面向对象的语言,我觉得除了对象名够长不容易记忆外。其它的都很好,且它是先编译成字节码然后由java虚拟机去运行的,不像 php 每次都需要去编译一次以后采取运行。

java对php curl 的实现

文件 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

{

/**

* 向指定URJxxqzNhIOL发送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 statiJxxqzNhIOc 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;

}

}

然后类似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://xxxxx.com/api/" +sid;

String data = HttpRequest.get(apiUrl,null); //开始模拟浏览器请求

JSONObject json = JSONObject.fromObject(data); //解析返回的json数据结果

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序如何获取用户信息
下一篇:微信支付功能接口测试用例(微信支付接口开发教程)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~