美文网首页swift实用功能
Swift URL" ? 转义后%3F "

Swift URL" ? 转义后%3F "

作者: Balopy | 来源:发表于2020-11-14 23:57 被阅读0次

今天搞一个老项目,使用的Moya+RXSwift,在做网络请求时,需要参数拼接到接后面,如下例子

let url = URL(string: "https://example.com")
let path = "/otherPath?name=wangDemo&age=18"
let urlWithPath = url?.appendingPathComponent(path)

print(urlWithPath)
// 输出:https://example.com/otherPath%3Fname=wangDemo&age=18

这样会报什么错?想知道的可以跑一下代码。
这个涉及URL编码url-encoding
,会把特殊符号给转义,? 转义后即是%3F,我们正常请求一般不会有问题,但是用appendingPathComponent就会有转义的问题,说到这大家应该知道怎么解决了吧。

import Foundation

public extension URL {

    /// Initialize URL from Moya's `TargetType`.
    init<T: TargetType>(target: T) {
        // When a TargetType's path is empty, URL.appendingPathComponent may introduce trailing /, which may not be wanted in some cases
        // See: https://github.com/Moya/Moya/pull/1053
        // And: https://github.com/Moya/Moya/issues/1049
        let targetPath = target.path
        if targetPath.isEmpty {
            self = target.baseURL
        } else {
         //   self = target.baseURL.appendingPathComponent(targetPath)
          //修改如下,如果有更好的方法,欢迎补充
            let urlWithPath = target.baseURL.absoluteString + targetPath
            self = URL(string: urlWithPath) ?? target.baseURL
        }
    }
}

相关文章

  • Swift URL" ? 转义后%3F "

    今天搞一个老项目,使用的Moya+RXSwift,在做网络请求时,需要参数拼接到接后面,如下例子 这样会报什么错?...

  • 网址URL中特殊字符转义编码

    网址URL中特殊字符转义编码字符 - URL编码值 URL特殊字符转义,URL中一些字符的特殊含义,基...

  • url转义

    URL中的字符只能是ASCII字符,但是ASCII字符比较少,而URL则常常包含ASCII字符集以外的字符,如非英...

  • url转义

    https://blog.csdn.net/qq_44724176/article/details/1016879...

  • golang标准库之net/url包

    完整的URL格式为: URL Values Query转义

  • url参数中特殊字符转义

    特殊字符转义%%25=%3d+%2b/%2f#%23?%3f空格+

  • spring RestTemplate 天坑

    url中%是特殊的字符,会被转义 %25 。被转义之后的URL不是正确的URL地址,程序会报出错误的400 Bad...

  • golang net/url包使用

    1.net/url简介 import "net/url"url包解析URL并实现查询转义 URL结构体 func ...

  • 转义

    URL 对URL中的中文进行转义encodeURI和decodeURI,decodeURIComponent和en...

  • Content-Type: form-data

    swift: varurlRequest =URLRequest(url: url!) urlRequest.ht...

网友评论

    本文标题:Swift URL" ? 转义后%3F "

    本文链接:https://www.haomeiwen.com/subject/tgmgbktx.html