转载自:https://www.reddit.com/r/swift/comments/2w19kp/how_do_you_send_a_through_nsmutableurlrequest/

how do you send a ? through NSMutableURLRequest without encoding the ? as %3F (self.swift)

submitted 1 year ago by xStory_Timex

I have a enum Router.swift that helps me use alamofire to interact with my API.

recently i changed the API and now when i send a URL request my code changes the "?" to "%3F" which i believe is "?" in url encoding.

here is the code Look at .ReadBrandProducts /products?brand_id=(id) when the id is 1 the request comes back as /products%3Fbrand_id=1

var path: String {
switch self {
case .AddReview(let id, _):
return "/products/\(id)/reviews"
case .ReadBrands:
return "/brands"
case .ReadBrandProducts(let id):
return "/products?brand_id=\(id)"
case .ReadProductData(let id):
return "/products/\(id)"
case .ReadReviews(let id):
return "/products/\(id)/reviews"
case .Favorite(let id):
return "/products/\(id)/favorite"
case .readFeed:
return "/activity"
}
} // MARK: URLRequestConvertible var URLRequest: NSURLRequest {
let URL = NSURL(string: Router.baseURLString)!
let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
mutableURLRequest.HTTPMethod = method.rawValue if let token = KeychainService.loadToken() {
mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
 
 
 
 
sorted by:

best
 
 

[–]lyinstevemod 2 points 1 year ago

If you're using Alamofire, you should really be submitting URL encoded parameters as a dictionary instead, because Alamofire handles serialization. You're doing more work than you should.

 

[–]xStory_Timex[S] 1 point 1 year ago

I don't understand, can you explain more

 

[–]lyinstevemod 1 point 1 year ago

So right now you're adding URL parameters, right? And you're serializing them into a string yourself.

You also said you're using Alamofire. Alamofire will actually take those arguments in a Dictionary as a parameter to the request() function. You don't need to -- and shouldn't -- manually create those strings.

Specifically just

?brand_id=\(id)

Instead, pass the parameters into the Alamofire request() function.

Alamofire.request(
.GET,
"/products",
parameters: ["brand_id": id]
)
 
 
 
 
 
 
 
 
 
 
 
 
 

QuestionQuestion mark is HTML escaped in NSMutableURLRequest self.iOSProgramming

Submitted 4 months ago by fourth_throwaway

ok, so I have an API that I built using ruby on rails. Pagination works completely in both the website and the API. Here is the api: https://sheltered-shelf-7331.herokuapp.com/api/yaks?page=1

just change out "page=1" at the end for "page=2" or "3", etc, and you'll see it works.

the problem though is that the "?" is read by the URL request as "%3F". Here is how the url request is printed in the console in Xcode:

  URL: https://sheltered-shelf-7331.herokuapp.com/api/yaks%3F

So of course it has a response of html status code 404. How can I make the question mark not be converted to %3F in the URL? I'm using URLRequest Convertible. Here is my code:

static let baseURL = "https://sheltered-shelf-7331.herokuapp.com"
let result: (path: String, parameters: [String: AnyObject]?) = { switch self {
case GetMainFeed:
return ("/api/yaks?", nil)
case PostLogin(let username, let password):
return ("/api/sessions", ["username": username, "password": password])
case PostCreateUser(let username, let password):
print(username, password)
return ("/api/users", ["username": username, "password": password])
case PostSendYak(let description, let image):
sending = true
return ("/api/yaks", ["description": description, "image": image])
case GetMyYaks:
sending = true
return ("/api/my-yaks", nil)
}
}() let url = NSURL(string: Router.baseURL)
let URLRequest = NSMutableURLRequest(URL: (url?.URLByAppendingPathComponent(result.path))!)
let encoding = Alamofire.ParameterEncoding.JSON
print(URLRequest)
if sending == true {
let defaults = NSUserDefaults.standardUserDefaults()
if let token = defaults.objectForKey("auth_token") as? String {
print(token)
URLRequest.setValue(token, forHTTPHeaderField: "Authorization")
} }
URLRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
let (encodedRequest, _) = encoding.encode(URLRequest, parameters: result.parameters)
encodedRequest.HTTPMethod = method.rawValue
return encodedRequest
 
 
 
all 3 comments
sorted by:

best
 
 

[–]Power781 2 points 4 months ago

It's not how URL parameters work.
the endpoint is /api/yaks
page=x is a parameter of your call.
you just have to set the encoding to let encoding = Alamofire.ParameterEncoding.URL depending on if you have URL parameters or body parameters.
Example on how I did it :

    public var parametersEncoding: Alamofire.ParameterEncoding {
switch self.method {
case .GET :
return .URL
case .POST, .PUT:
return .JSON
default:
return .JSON
}
}
 
 
 
 

[–]AyyBodyFrizzesAlone 1 point 4 months ago

?page=1 is not a path component. It's a URI parameter. Just append it with stringByAppendingString.

 

[–]tonygoold 1 point 4 months ago

It's actually the query, not the parameter (which isn't used by HTTP), an important distinction if you're trying to get the query string from an NSURL. You're right about why it's encoding the question mark though.

%3f URL --> '?'拼接引发的问题的更多相关文章

  1. php 对url 操作类:url拼接、get获取页面、post获取页面(带传参)

    /* * @brief url封装类,将常用的url请求操作封装在一起 * */ class URL{ private $error; public function __construct(){ $ ...

  2. url拼接

    在做网页抓取的时候经常会遇到一个问题就是页面中的链接是相对链接,这个时候就需要对链接进行url拼接,才能得到绝对链接. url严格按照一定的格式构成,一般为如下5个字段: 详细可参考RFC:http: ...

  3. Python相对完美的URL拼接函数

    首先说下什么叫URL拼接,我们有这么一个HTML片段:   <a href="../../a.html">click me</a> 做为一只辛苦的爬虫,我们 ...

  4. url拼接参数格式

    在一些情况下,需要直接往url上拼接请求参数. http://www.yanggb.com?flag=1&type=normal&role=customer 通过上面的例子就可以看出, ...

  5. Ajax获取接口数据,url拼接参数跳转页面,js获取上一级页面参数给本页面

    1.Ajax获取接口数据 function demo(){ //假设请求参数 var requestBody = [{ "name":"zhang", &quo ...

  6. 字符串拼接引发的BUG

    译者按: bug虽小,却是个磨人的小妖精! 原文: Fixing a bug: when concatenated strings turn into numbers in JavaScript 译者 ...

  7. 接口测试get请求url拼接函数(python)

    get请求地址一般是 协议+域名+端口+路径+参数,除了协议和域名其他均可为空.  http(s)://domain:port/path?key1=value1&key2=value2& ...

  8. 相对URL拼接为绝对URL的过程

    URL有两种方式:绝对的和相对的. 绝对URL中包含有访问资源的所需的全部信息 举一个例子: <HTML> <HEAD><TITLE>Joe's Tools< ...

  9. 关于url拼接传参数和利用view的字典传参数时,模板获取数据的方式问题

    url = "{% url 'dashboard:internship-theme-stat' %}?teacher_name="+teacher_name+"& ...

随机推荐

  1. 一、链接Sql Server2014提示找不到实例的问题解决方案

    在登录数据库时,确认数据库地址.用户名.密码正确的情况下,却报如下错误,则说明目标数据库服务器有相应的服务未启动. 在目标数据库服务器中打开服务列表: 找到SQL Server(****)服务(括号中 ...

  2. openwrt设置语言的过程

    设置语言的流程一.关联的配置文件/etc/config/luci查看配置文件内容如下:root@hbg:/# cat /etc/config/luci config core 'main'       ...

  3. OMCS开发手册(04) -- 二次开发流程

    在掌握了前面几篇关于OMCS的详细介绍后,我们就可以正式基于OMCS进行二次开发了.下面我们就从服务端和客户端的角度分别介绍开发的步骤. 一.服务端开发 抛开具体的业务逻辑而言,就OMCS的服务端的开 ...

  4. 2016NEFU集训第n+3场 G - Tanya and Toys

    Description In Berland recently a new collection of toys went on sale. This collection consists of 1 ...

  5. 常量指针(const X*)和指针常量(X* const)

    const X* 类型的指针(指向常量的指针),此指针的地址是一个变量,是可以修改的:但其所指向的内容是常量,是不可以修改的. 例如: 1: char name[5] = "lisi&quo ...

  6. F - 小晴天老师系列——苹果大丰收

    F - 小晴天老师系列——苹果大丰收 Time Limit: 2000/1000MS (Java/Others)    Memory Limit: 128000/64000KB (Java/Other ...

  7. centos 10字母随机文件病毒清理

    病毒表现:网络流量暴满,疯狂地向香港的一个IP发数据,同时在top里面表现为随机的10位字母的进程,看/proc里面的信息,则为ls,cd之类常见的命令,CPU利用率也在top之首.杀死该进程后,会再 ...

  8. @ResponseBody返回json时,json数据丢失或者报错

    现象: 1.报错:There is a cycle in the hierarchy! 2.返回至前台的json不完整,字段丢失. 错误原因: eg:entity1的属性有list<entiti ...

  9. 在TextView上显示图片信息

    布局文件 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:t ...

  10. Javascript和HTML dom

    今天在看DOM那一章的时候突然想到一个问题,众所周知的js的数据类型有两种:原始类型和对象类型.其中原始类型又包括以下几种类型:数字型.字符串型.布尔值.null和undefined.其中对象类型包括 ...