前言

项目是基于python3的pc桌面项目。因为需要对外发布web服务进行数据交换所以需要支持web服务。项目主要使用了get,post服务请求。

一、python3中怎样进行发送web请求?

python3使用urllib模块实现web请求,可以支持get和post请求。

二、使用步骤

 1.引入python库

import http.client
import urllib,parser

urlpre = '127.0.0.1'

2.get服务

def gettoremote(url):
 conn = http.client.httpconnection(urlpre,8082, timeout=10)
 conn.request( "get" , url)
 response = conn.getresponse()
 conn.close
 return response

3.post服务

def posttoremote(url,data):
 params = urllib.parse.urlencode(data)
 # post 请求数据,要带上 content-type 字段,以告知消息主体以何种方式编码
 headers = { "content-type" : "application/json"}
 conn = http.client.httpconnection(urlpre,8082, timeout=10)
 conn.request( "post" , url ,params,headers)
 response = conn.getresponse()
 conn.close
 return response

	#调用post请求
 cpparams = []
 for i in range(0,len(data),1):
  cpparams.append(data[i]['path'])
  cpparams.append(data[i]['id'])
  cpparams.append(data[i]['name'])
 posttoremote('/copy',{'params':cpparams})

总结

到此这篇关于python程序调用远程服务的步骤详解的文章就介绍到这了,更多相关python程序调用远程服务内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!