您的位置:首页 > 编程语言 > PHP开发

【学习|总结】如何使用java和php发送http请求

2018-10-21 14:24 113 查看

第一篇博客写什么呢=w=看看下面的吧

最近在学php后台开发,遇到一个学号验证问题,所以需要携带token请求学校接口返回学生信息,通过解析json来获取学生学号。这让我想起大一下学期做java音乐播放器时也涉及到了请求接口的问题,下面来看一下具体实现吧~

  • java发送请求并接收返回的json对象

工具包:

  1. httpClient相关包:在jdk中自带直接
    import
    就好;
  2. json相关包:点这里下载

java携带请求头发送http请求分为七步:

  1. 创建httpClient对象;
  2. 创建请求对象(get/post/delete),并设置请求的url;
  3. 往请求头中加入一个键值对
  4. 用httpClient对象的
    execute()
    方法执行请求;
  5. 用HttpResponse的
    getEntity()
    方法获取httpEntity对象,该对象包含了服务器的响应内容。
  6. 关闭响应对象;
  7. 关闭httpClient。

具体参见如下代码(以GET为例):

package test.yubei.com.app.api;

import java.io.IOException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class DoGet {

/*执行GET请求
*
*@param String api:要请求的url
*@param String token:用户token
*@return JSONObject
*
*/
public static JSONObject doGet(String api,String token){
try {
//1、创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2、创建get对象,设置url
HttpGet get = new HttpGet(api);
//3.往请求头中加入一个键值对
get.setHeader("Authorization",token);
//3、执行get请求
CloseableHttpResponse response = httpClient.execute(get);
/*
* HttpResponse的getEntity()方法可获取HttpEntity对象,
* 该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
*/
String str = EntityUtils.toString(response.getEntity());
response.close();   //关闭响应对象
httpClient.close();     //关闭httpClient
JSONObject jsonObject = new JSONObject(str);    //将服务器响应内容变成json对象
return jsonObject;
} catch (JSONException | IOException e) {
return null;
}
}
}
  • PHP携带请求头发送请求并解析返回的json

cURL是一个利用URL语法在命令行下工作的文件传输工具。cURL支持的通信协议有FTP、FTPS、HTTP、HTTPS等。PHP可使用cURL库快速发送请求然后获得服务器响应内容,下面介绍几个cURL常用函数:

  1. curl_init()

初始化cURL会话,返回 cURL 句柄,供

curl_setopt()
curl_exec()
curl_close()
函数使用。

  1. curl_setopt ( resource $ch , string $option , mixed $value )

为 cURL 会话句柄设置选项,返回值为布尔值。

这里的

$option
参数是你想要的设置,
$value
是给这个
$option
指定的值。

官方文档中

$option
int
类型,但是经过实践我认为是字符串类型,所以修改为了
string

这么写可能有点抽象还是写不清楚这两个参数是干什么的,举个例子吧!

eg:

$option
CURLOPT_RETURNTRANSFER
的功能为设置传输方式,我想要直接输出响应内容,于是我设置
$value
为0。我想要传输数据用别的变量来接它,于是我设置
$value
为1。

  1. curl_exec ( resource $ch )

执行给定的 cURL 会话。这个函数应该在初始化一个 cURL 会话并且设置完全部的选项后被调用。

  1. curl_close ( resource $ch )

关闭 cURL 会话并且释放所有资源,返回值为空。cURL 句柄也会被删除。

下面来看一个具体的例子吧:

<?php

/*执行GET请求
*
*@param String $url:url
*@return json
*/
function doGet($url){
1d810

//1、curl初始化
$ch = curl_init();
//2、设置URL
curl_setopt($ch, CURLOPT_URL, $url);
//3、设置传输方式,参数为1表示传输数据,为0表示直接输出显示。
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//4、设置请求头
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Authorization:$token"));
//5、执行请求
$output = curl_exec($ch);
if(empty($output)){
echo makeErrJson(50001,"Internal Server Error");
}else{
$data = json_decode($output,true);
return $data;
}
//6、用完记得关掉
curl_close($ch);
}

/*执行POST请求
*
*@param String $url:url
*@return json
*/
function doPost($url){
//1、curl初始化
$ch = curl_init();
//2、设置URL
curl_setopt($ch, CURLOPT_URL, $url);
//3、设置传输方式,参数为1表示传输数据,为0表示直接输出显示。
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//4、设置post方式提交
curl_setopt($curl, CURLOPT_POST, 1);
//5、设置post数据
$post_data = array(
"stuno" => "17051804",
"name" => "yubei"
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
//6、设置请求头
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Authorization:$token"));
//7、执行请求
$output = curl_exec($ch);
if(empty($output)){
echo makeErrJson(50001,"Internal Server Error");
}else{
$data = json_decode($output,true);
return $data;
}
//8、用完记得关掉
curl_close($ch);
}

/*生成错误信息json
*
*@param String $code:错误代码
*@param String $msg:错误信息
*@return json
*/
function makeErrJson($code,$msg){
$json = array(
"error" => $code,
"msg" => $msg
);
return json_encode($json);
}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: