使用GET方法访问网站

使用GET方法访问网站

服务器接收get参数

server.py

import flask
app = flask.Flask(__name__)
@app.route('/')
def index():
    province = flask.request.args.get('province')
    city = flask.request.args.get('city')
    print(province, city)
    return province+","+city

debug=True
if __name__ == '__main__':
    app.run()

client.py

import urllib.request
url = "http://127.0.0.1:5000"
province = "山东"
city = "青岛"
# 对汉字编码
province = urllib.parse.quote(province)
city = urllib.parse.quote(city)
# 拼接字符串
data = "province=" + province + "&city=" + city
response = urllib.request.urlopen(url+"?"+data)
data = response.read()
content = data.decode()
print(content)

# try:
#     # 模拟浏览器向服务器发送请求
#     response = urllib.request.urlopen(url+"?"+data)
#     data = response.read()
#     content = data.decode()
#     print(content)
# except urllib.error.HTTPError:
#     print('HTTPError异常')
# except urllib.error.URLError:
#     print('URLError异常')

 

 

客户端发送get请求

server.py

import flask
from flask import Flask

app = Flask(__name__)
@app.route('/')
def index():
    lang = flask.request.values.get("lang","")
    if lang == "chinese":
        html = "大家好"
    else:
        html = "hello"
    return html

app.debug = True
app.run()

client.py

import urllib.request
url = "http://127.0.0.1:5000"
response = urllib.request.urlopen(url+"?lang=english")
content = response.read()
print(content)
html = content.decode()
print(html)

中文字符串参数编码

Server.py

import flask
app = flask.Flask(__name__)

@app.route('/')
def index():
    dict = {"苹果": "apple", "桃子": "peach", "梨子": "pear"}
    word = flask.request.values.get("word", "")
    if word in dict.keys():
        s = dict[word]
    else:
        s = "字典里无该词"
    return s

debug = True
if __name__ == '__main__':
    app.run()

Client.py

import urllib.request
import urllib.parse

url = "http://127.0.0.1:5000"
word = input("请输入中文:")
word = urllib.parse.quote(word)
response = urllib.request.urlopen(url+"?word="+word)
content = response.read()
html = content.decode("utf-8")
print(html)

 

 

Requests中的GET

server.py

import flask
app = flask.Flask(__name__)

@app.route('/')
def index():
    try:


        province = flask.request.values.get('province', "")
        city = flask.request.values.get('city', "")
        return province + "," + city
    except Exception as e:
        return str(str)

debug = True
if __name__ == '__main__':
    app.run()

client.py

import requests
url = "http://127.0.0.1:5000"

try:
    response = requests.get(url, params={"province": "山东", "city": "青岛"})
    print(response.content)
    print(response.text)
except Exception as e:
    print(e)

 

posted @ 2024-05-18 19:49  JJJhr  阅读(9)  评论(0编辑  收藏  举报