Skip to content

PHP CURL请求的小细节 #53

Closed
Closed
@Wscats

Description

@Wscats
Owner

在模拟浏览器请求的时候,要注意如果URL中包含了中文字符串要进行处理,具体可以用urlencode函数来进行转换,不然模拟的请求会失败,还有模拟请求头也要尽可能一样
这个URL是可以的,因为科技已经转换为**%E7%A7%91%E6%8A%80**
$url = 'http://115.28.54.40:8080/beautyideaInterface/api/v1/resources/search_res?condition=%E7%A7%91%E6%8A%80&imieId=771151417E03687F75D855F69DA18724&pageNo=10&pageSize=10';
这个URL是不可以的,因为URL在CURL请求中带了中文会失效
$url = 'http://115.28.54.40:8080/beautyideaInterface/api/v1/resources/search_res?condition='.urlencode('科技').'&imieId=771151417E03687F75D855F69DA18724&pageNo=10&pageSize=10

  • urlencode()函数原理就是首先把中文字符转换为十六进制,然后在每个字符前面加一个标识符%
  • urldecode()函数与urlencode()函数原理相反,用于解码已编码的 URL 字符串,其原理就是把十六进制字符串转换为中文字符
<?php
    //$url = 'http://115.28.54.40:8080/beautyideaInterface/api/v1/resources/search_res?condition=%E7%A7%91%E6%8A%80&imieId=771151417E03687F75D855F69DA18724&pageNo=10&pageSize=10';
    $url = 'http://115.28.54.40:8080/beautyideaInterface/api/v1/resources/search_res?condition='.urlencode('科技').'&imieId=771151417E03687F75D855F69DA18724&pageNo=10&pageSize=10';
    $ch = curl_init();
    $header = array(
        'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding:gzip, deflate, sdch',
        'Accept-Language:zh-CN,zh;q=0.8',
        'Cache-Control:max-age=0',
        'Connection:keep-alive',
        'Host:115.28.54.40:8080',
        'Upgrade-Insecure-Requests:1',
        'User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1',
    );
    curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 执行HTTP请求
    curl_setopt($ch , CURLOPT_URL , $url);
    $res = curl_exec($ch);
    echo $res;
?>

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @Wscats

        Issue actions

          PHP CURL请求的小细节 · Issue #53 · Wscats/articles