복붙노트

[PYTHON] POST 요청을 보내는 방법?

PYTHON

POST 요청을 보내는 방법?

온라인에서이 스크립트를 발견했습니다.

import httplib, urllib
params = urllib.urlencode({'number': 12524, 'type': 'issue', 'action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded",
            "Accept": "text/plain"}
conn = httplib.HTTPConnection("bugs.python.org")
conn.request("POST", "", params, headers)
response = conn.getresponse()
print response.status, response.reason
302 Found
data = response.read()
data
'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
conn.close()

그러나 나는 PHP와 함께 사용하는 방법이나 params 변수 안의 모든 것과 사용 방법을 이해하지 못합니다. 이 기능을 작동 시키려고 약간의 도움을받을 수 있습니까?

해결법

  1. ==============================

    1.파이썬을 사용하여 HTTP로 처리하려는 경우 Requests : HTTP for Human을 사용하는 것이 좋습니다. 귀하의 질문에 적합한 POST 빠른 시작은 다음과 같습니다.

    파이썬을 사용하여 HTTP로 처리하려는 경우 Requests : HTTP for Human을 사용하는 것이 좋습니다. 귀하의 질문에 적합한 POST 빠른 시작은 다음과 같습니다.

    >>> import requests
    >>> r = requests.post("http://bugs.python.org", data={'number': 12524, 'type': 'issue', 'action': 'show'})
    >>> print(r.status_code, r.reason)
    200 OK
    >>> print(r.text[:300] + '...')
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <title>
    Issue 12524: change httplib docs POST example - Python tracker
    
    </title>
    <link rel="shortcut i...
    >>> 
    
  2. ==============================

    2.스크립트를 이식 가능하게하고 제 3 자 의존성을 필요로하지 않는다면 이것은 순전히 파이썬 3에서 POST 요청을 보내는 방법입니다.

    스크립트를 이식 가능하게하고 제 3 자 의존성을 필요로하지 않는다면 이것은 순전히 파이썬 3에서 POST 요청을 보내는 방법입니다.

    from urllib.parse import urlencode
    from urllib.request import Request, urlopen
    
    url = 'https://httpbin.org/post' # Set destination URL here
    post_fields = {'foo': 'bar'}     # Set POST fields here
    
    request = Request(url, urlencode(post_fields).encode())
    json = urlopen(request).read().decode()
    print(json)
    

    샘플 출력 :

    {
      "args": {}, 
      "data": "", 
      "files": {}, 
      "form": {
        "foo": "bar"
      }, 
      "headers": {
        "Accept-Encoding": "identity", 
        "Content-Length": "7", 
        "Content-Type": "application/x-www-form-urlencoded", 
        "Host": "httpbin.org", 
        "User-Agent": "Python-urllib/3.3"
      }, 
      "json": null, 
      "origin": "127.0.0.1", 
      "url": "https://httpbin.org/post"
    }
    
  3. ==============================

    3.urllib (GET 전용)을 사용하여 POST 요청을 수행 할 수 없으며 대신 요청 모듈을 사용해보십시오 (예 :

    urllib (GET 전용)을 사용하여 POST 요청을 수행 할 수 없으며 대신 요청 모듈을 사용해보십시오 (예 :

    보기 1.0 :

    import requests
    
    base_url="www.server.com"
    final_url="/{0}/friendly/{1}/url".format(base_url,any_value_here)
    
    payload = {'number': 2, 'value': 1}
    response = requests.post(final_url, data=payload)
    
    print(response.text) #TEXT/HTML
    print(response.status_code, response.reason) #HTTP
    

    예제 1.2 :

    >>> import requests
    
    >>> payload = {'key1': 'value1', 'key2': 'value2'}
    
    >>> r = requests.post("http://httpbin.org/post", data=payload)
    >>> print(r.text)
    {
      ...
      "form": {
        "key2": "value2",
        "key1": "value1"
      },
      ...
    }
    

    예제 1.3 :

    >>> import json
    
    >>> url = 'https://api.github.com/some/endpoint'
    >>> payload = {'some': 'data'}
    
    >>> r = requests.post(url, data=json.dumps(payload))
    
  4. ==============================

    4.

    import UIKit
    import Alamofire
    import SwiftyJSON
    
    class HttpNetwork: NSObject {
    func networkCall(parameter:Parameters?,callType:HTTPMethod,Url:String,headerParam:[String:String]? ,completion: @escaping (_ swift_result: JSON?,_ errorMessage:String?) -> Void){
    
    
        debugPrint("\\\\\\\\\\\\\\\\\\\\\\\\\\\\API_INFO\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\")
        debugPrint("================\(callType.rawValue)=====================")
        debugPrint("PARAM==========\(String(describing: parameter))==============")
        debugPrint("HEADERS==============\(String(describing: headerParam))=====================================")
    
        let url:String?
    
            url = Url
    
        debugPrint("URL==============\(String(describing: url))=======================")
    
        if (NetworkReachabilityManager()?.isReachable == false){
    
    
            completion(nil, "Please check your internet connection")
        }
        else{
    
            Alamofire.request(url!, method:callType, parameters:parameter,encoding: JSONEncoding.default, headers: headerParam).responseJSON {
                response in
    
                if let bytes = response.data {
                    if let response = String(bytes: bytes, encoding: .utf8) {
                        print("API RESPONSE : \(response)")
                    }
                }
    
                switch response.result {
                case .success:
    
                    do{
    
                        let swifty_object = try JSON(data: response.data!)
    
                        if swifty_object["status"].bool == true{
    
                            completion(swifty_object,nil)
                        }
                        else{
    
                            completion(nil,swifty_object["message"].description)
                        }
    
    
                    }
                    catch{
    
                        completion(nil,error.localizedDescription)
    
                    }
                    break
                case .failure(let error):
    
                    completion(nil,error.localizedDescription)
    
                }
            }
        }
    }
    
    
    func uploadImageToServerByMultiPart(targetImage:UIImage,targetUrl:String,withName_OR_paramKey:String,headerParam:[String:String]?,completion:@escaping (_ swift_result: JSON?,_ errorMessage:String?) -> Void){
    
        let imageData = UIImageJPEGRepresentation(targetImage, 1.0)
    
        if (NetworkReachabilityManager()?.isReachable == false){
    
           completion(nil, "Please check your internet connection")
    
        }
        else{
    
    
            Alamofire.upload(multipartFormData: { (multipartFormData) in
                multipartFormData.append(imageData!, withName: withName_OR_paramKey, fileName: "file.jpeg", mimeType: "image/jpeg")
            }, to: targetUrl, method:.put, headers:headerParam)
            { (result) in
                //
                switch result {
                case .success(let upload, _, _):
                    upload.uploadProgress { progress in
    
                        print("completed : \(progress.fractionCompleted) ")
                        // DEVELOPER : FRACTION HUD USED
                        //hud.progress = Float(progress.fractionCompleted)
    
                    }
    
                    upload.responseJSON { response in
                        debugPrint(response)
    
                        if(response.result.isSuccess)
                        {
    
                            let httpStatusCode = response.response?.statusCode
                            if httpStatusCode == 201 || httpStatusCode == 200{
                                //SDImageCache.shared().store(image, forKey: self.user_image_file_url)
                                do{
    
                                    let swifty_object = try JSON(data: response.data!)
                                    completion(swifty_object,nil)
                                }
                                catch{
    
                                    completion(nil,error.localizedDescription)
                                }
    
                            }
                            else{
    
                                completion(nil,response.result.error!.localizedDescription)
                            }
    
                        }
                        if(response.result.isFailure){
    
                            completion(nil,response.result.error!.localizedDescription)
    
    
                        }
                    }
                case .failure(let encodingError):
    
                     completion(nil,encodingError.localizedDescription)
    
    
                }
            }
    
        }
    }
    
    
    }
    
  5. from https://stackoverflow.com/questions/11322430/how-to-send-post-request by cc-by-sa and MIT license