Swift请求不起作用

时间:2017-06-10 06:57:34

标签: swift

我试图使用此链接https://congress.api.sunlightfoundation.com/bills/search?query=Taylor强制法案来查询账单。

在我的iOS应用中,我尝试使用postString参数(" query =" TaylorForcedAct")来获取我在相同网址上输入的结果网页浏览器。不幸的是,在使用Swift时,我收到403错误:

status code: 403, headers { "Content-Length" = 551; "Content-Type" = "text" 

如果我在浏览器中这样做,它会成功返回数据。

我无法通过请求使用swift访问它,仅在地址栏中,为什么?]

编辑:抱歉所有的错误,我在深夜写的这里是快速的代码

func authentication3() {


let request = NSMutableURLRequest(url: URL(string: "https://congress.api.sunlightfoundation.com/bills/search?")!)
request.httpMethod = "GET"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Accept")



//let poststring = "query= TaylorForceAct"
request.httpBody = "query=TaylorForceAct".data(using: String.Encoding.utf8)
//request.addValue("\"Taylor Force Act\"", forHTTPHeaderField: "query")
let task = URLSession.shared.dataTask(with: request as URLRequest) {
    data, response, error in

    if error != nil {
        print("error=\(String(describing: error?.localizedDescription))")
        return
    }

    print("response = \(String(describing: response))")

    print("Requestttt = \(String(describing: request.url?.absoluteURL))")

    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
    print("responseString = \(responseString ?? "L")")
   }
task.resume()
   }

和回复:

Optional(<NSHTTPURLResponse: 0x608000038040> { URL: https://congress.api.sunlightfoundation.com/bills/search? } { status code: 403, headers {
    "Content-Length" = 551;
    "Content-Type" = "text/html";
    Date = "Sat, 10 Jun 2017 16:57:23 GMT";
    Server = CloudFront;
    Via = "1.1 b4b2849aaf2c14969531f9514611da28.cloudfront.net (CloudFront)";
    "x-amz-cf-id" = "vH379ZK57HN6pqgCQsdWD7x_jv5_xTzB5uMX3krdoSRR92pKFKWeag==";
    "x-cache" = "Error from cloudfront";
} })
Requestttt = Optional(https://congress.api.sunlightfoundation.com/bills/search?)
responseString = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD><BODY>
<H1>ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Bad request.
<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: vH379ZK57HN6pqgCQsdWD7x_jv5_xTzB5uMX3krdoSRR92pKFKWeag==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>

浏览器的响应使用相同的参数和网址(https://congress.api.sunlightfoundation.com/bills/search?query=TaylorForceAct):

{"results":[],"count":0,"page":{"count":0,"per_page":20,"page":1}}

解决方案:我是一个白痴,试图用GET发布...正确的解决方案就是选择的答案是:使用URLcomponets一起解析网址。

3 个答案:

答案 0 :(得分:2)

  

我正在尝试使用postString参数

如果我理解正确,您使用的是POST方法。

这是不正确的。当您向浏览器写入URL时,使用GET方法。

您将获得POST的403(禁止)回复。搜索API显然不支持此方法(在REST客户端中确认):

答案 1 :(得分:1)

此特定网络服务需要GET个请求。如果请求是POST请求,它会向您发送403状态代码。

我还建议对请求进行百分比编码(例如,您可以使用URLComponents为您执行此操作)。因此:

var components = URLComponents(string: "https://congress.api.sunlightfoundation.com/bills/search")!
let item = URLQueryItem(name: "query", value: "\"Taylor Force Act\"")
components.queryItems = [item]
let request = URLRequest(url: components.url!)

答案 2 :(得分:-1)

403错误代码表示禁止访问。在某些服务中,原因是缺少指定的User-Agent http请求标头。您可以尝试以下代码:

UserDefaults.standard.register(defaults: ["UserAgent": "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36"])

再次测试您的请求