본문 바로가기

개발/Python & Flask

Python requests String 데이터 전송, Curl post data 기본 인코딩

서론

import requests
Output = requests.post('https://ui.teledit.com/Danal/TGW/request.php', headers=headers, data=arg)

Django 서버 → PHP 서버

POST 데이터 전송이 아무리 해도 데이터를 못 받았다.

curl -k https://ui.teledit.com/Danal/TGW/request.php -d "COMMAND=ITEMSEND2;ID=A010002002;PWD=bbbbb;ITEMCOUNT=1;ITEMINFO=1|301|1|1270000000|teleditwebtest;"

이렇게 했을 땐 너무 전송이 잘됐다.

 

무슨 차이인지 알아보자.

 

Python Requests String 데이터 전송

import requests
Output = requests.post('https://ui.teledit.com/Danal/TGW/request.php', headers=headers, data=arg)

보통 json 형태로 넘기는데 일반 String 은 저렇게 넘긴다.

문자열 형태로 넘기면 안되고, encode('utf-8') 과 같이 인코딩을 꼭 하여

"바이트코드" 의 형태로 전달된다.

한글 인코딩 형태는 총 4가지, 

UTF-8, EUC-KR, CP949, Unicode 가 있다. (EUC-KR 상위호환이 CP949, Unicode와 UTF-8도 같은 계열이긴 하다)

여기 아주 정리가 잘되어있다. https://redscreen.tistory.com/163

 

CURL Post Data 전송 기본 인코딩

curl verbose 출력을 보면 알 수 있는데,

C:\Users\tmddud333>curl -k https://ui.teledit.com/Danal/TGW/request.php -d "COMMAND=ITEMSEND2;ID=A010002002;PWD=bbbbb;ITEMCOUNT=1;ITEMINFO=1|301|1|1270000000|teleditwebtest;" -v
*   Trying 150.242.132.113:443...
* Connected to ui.teledit.com (150.242.132.113) port 443 (#0)
* schannel: disabled automatic use of client certificate
* schannel: ALPN, offering http/1.1
* ALPN, server did not agree to a protocol
> POST /Danal/TGW/request.php HTTP/1.1
> Host: ui.teledit.com
> User-Agent: curl/7.79.1
> Accept: */*
> Content-Length: 97
> Content-Type: application/x-www-form-urlencoded
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Fri, 20 May 2022 05:48:57 GMT
< Server: Apache
< Expires: 0
< Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
< Pragma: no-cache
< Content-Length: 172
< Content-Type: text/plain; charset=euc-kr
<
Result=0
ServerInfo=642e12b33b7004d6eb57628f509826dbb60ee0911fcf3927970eda41091fac2bafda18aca232a4a0527dcf0c72aee702da40c32ecf1f53caa137f47efebdafe7
ErrMsg=No Information* Connection #0 to host ui.teledit.com left intact

> 표시는 request header

< 표시는 response header 이다.

request header 를 보면 application/x-www-form-urlencoded 인 것으로 확인된다.

따라서 Python 코드에 header 를 추가하고 위와 같이 설정해주면 된다.

해결방안

import requests

headers = {'Content-Type': 'application/x-www-form-urlencoded'}
arg=MakeParam(TransData).encode('euc-kr')
print('arg=',arg)
Output = requests.post('https://ui.teledit.com/Danal/TGW/request.php', headers=headers, data=arg)

위와 같이 해결했다.

반응형