GVKun编程网logo

Python发送带有标头的POST(python post请求带headers)

7

在本文中,我们将给您介绍关于Python发送带有标头的POST的详细内容,并且为您解答pythonpost请求带headers的相关问题,此外,我们还将为您提供关于.NET:发送带有数据的POST和读

在本文中,我们将给您介绍关于Python发送带有标头的POST的详细内容,并且为您解答python post请求带headers的相关问题,此外,我们还将为您提供关于.NET:发送带有数据的POST和读取响应的最简单方法、aiohttp 如何发送带有标头的请求、C#通过HttpWebRequest发送带有JSON Body的POST请求实现、PostgreSQL PL / Python如何在性能方面与Python之外的Python进行比较?的知识。

本文目录一览:

Python发送带有标头的POST(python post请求带headers)

Python发送带有标头的POST(python post请求带headers)

我尝试构建一个python脚本,该脚本发送带有用于提取结果的参数的POST。通过提琴手,我提取了我要返回的帖子请求。该网站仅使用https。

POST /Services/GetFromDataBaseVersionned HTTP/1.1Host: www.mywbsite.fr"Connection": "keep-alive","Content-Length": 129,"Origin": "https://www.mywbsite.fr","X-Requested-With": "XMLHttpRequest","User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5","Content-Type": "application/json","Accept": "*/*","Referer": "https://www.mywbsite.fr/data/mult.aspx","Accept-Encoding": "gzip,deflate,sdch","Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4","Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3","Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"{"isLeftColumn":false,"lID":-1,"userIpCountryCode":"FR","version":null,"languageCode":"fr","siteCode":"frfr","Quotation":"eu"}

现在我的python脚本:

#!/usr/bin/env python# -*- coding: iso-8859-1 -*-import stringimport httplibimport urllib2host = "www.mywbsite.fr/sport/multiplex.aspx"    params=''"isLeftColumn":"false","liveID":"-1","userIpCountryCode":"FR","version":"null","languageCode":"fr","siteCode":"frfr","Quotation":"eu"''headers = { Host: www.mywbsite.fr,"Connection": "keep-alive","Content-Length": 129,"Origin": "https://www.mywbsite.fr","X-Requested-With": "XMLHttpRequest","User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5","Content-Type": "application/json","Accept": "*/*","Referer": "https://www.mywbsite.fr/data/mult.aspx","Accept-Encoding": "gzip,deflate,sdch","Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4","Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3","Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=;     GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"}url = "/Services/GetFromDataBaseVersionned"# POST the requestconn = httplib.HTTPConnection(host,port=443)conn.request("POST",url,params,headers)response = conn.getresponse()data = response.read()print data

但是当我运行脚本时,出现以下错误:

socket.gaierror: [Errno -2] Name or service not known

答案1

小编典典

非常感谢您链接到请求模块。太完美了。下面解决我的问题。

import requestsimport jsonurl = ''https://www.mywbsite.fr/Services/GetFromDataBaseVersionned''payload = {    "Host": "www.mywbsite.fr",    "Connection": "keep-alive",    "Content-Length": 129,    "Origin": "https://www.mywbsite.fr",    "X-Requested-With": "XMLHttpRequest",    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5",    "Content-Type": "application/json",    "Accept": "*/*",    "Referer": "https://www.mywbsite.fr/data/mult.aspx",    "Accept-Encoding": "gzip,deflate,sdch",    "Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4",    "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",    "Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"}# Adding empty header as parameters are being sent in payloadheaders = {}r = requests.post(url, data=json.dumps(payload), headers=headers)print(r.content)

.NET:发送带有数据的POST和读取响应的最简单方法

.NET:发送带有数据的POST和读取响应的最简单方法

令我惊讶的是,在.NET BCL中,我无法说出这么简单的事情:

byte[] response = Http.Post(    url: "http://dork.com/service",    contentType: "application/x-www-form-urlencoded",    contentLength: 32,    content: "home=Cosby&favorite+flavor=flies");

上面的假设代码使用数据进行HTTP POST,并从Post静态类的方法返回响应Http

既然我们没有这么容易的事情,那么下一个最佳解决方案是什么?

如何发送带有数据的HTTP POST并获取响应的内容?

答案1

小编典典
   using (WebClient client = new WebClient())   {       byte[] response =       client.UploadValues("http://dork.com/service", new NameValueCollection()       {           { "home", "Cosby" },           { "favorite+flavor", "flies" }       });       string result = System.Text.Encoding.UTF8.GetString(response);   }

您将需要这些包括:

using System;using System.Collections.Specialized;using System.Net;

如果您坚持使用静态方法/类:

public static class Http{    public static byte[] Post(string uri, NameValueCollection pairs)    {        byte[] response = null;        using (WebClient client = new WebClient())        {            response = client.UploadValues(uri, pairs);        }        return response;    }}

然后简单地:

var response = Http.Post("http://dork.com/service", new NameValueCollection() {    { "home", "Cosby" },    { "favorite+flavor", "flies" }});

aiohttp 如何发送带有标头的请求

aiohttp 如何发送带有标头的请求

如何解决aiohttp 如何发送带有标头的请求?

import asyncio
import aiohttp
headers = {
    ''phone'': "Mymobile"
}


async def fetch(url,session):
    async with session.get(url,headers=headers) as response:
        res = await response.json()



async def main():
    async with aiohttp.ClientSession() as session:
        await fetch("https://www.kfc.ru/api/account/verify",session)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

错误:

headers=self.headers,aiohttp.client_exceptions.ContentTypeError: 0,message=''Attempt to decode JSON with unexpected mimetype: text/html; charset=utf-8'',url=URL(''https://www.kfc.ru/api/account/verify'')

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

C#通过HttpWebRequest发送带有JSON Body的POST请求实现

C#通过HttpWebRequest发送带有JSON Body的POST请求实现

起因

很多博客都有描述到这个问题,那么为什么我还要写一篇文章来说一下呢,因为其他的都似乎已经过时了,会导致其实body 并没有发送过去。至于为什么不使用其他的诸如 HttpClient 之类的,是由于业务需要。

原来的处理方式

通过 GetRequestStream 来获取请求流,后把需要发送的 Json 数据写入到流中

private T PostDataViaHttpWebRequest<T>(string baseUrl,
            IReadOnlyDictionary<string, string> headers,
            IReadOnlyDictionary<string, string> urlParas,
            string requestBody=null)
        {
            var resuleJson = string.Empty;
            try
            {
                var apiUrl = baseUrl;

                if (urlParas != null)
                    urlParas.ForEach(p =>
                    {
                        if (apiUrl.IndexOf("{" + p.Key + "}") > -1)
                        {
                            apiUrl = apiUrl.Replace("{" + p.Key + "}", p.Value);
                        }
                        else
                        {
                            apiUrl += string.Format("{0}{1}={2}", apiUrl.Contains("?") ? "&" : "?", p.Key, p.Value);
                        }
                    }
                );
                
                var req = (HttpWebRequest)WebRequest.Create(apiUrl);
                req.Method = "POST";
                req.ContentType = "application/json"; 
                req.ContentLength = 0;

                if (!requestBody.IsNullOrEmpty())
                {
                    using (var postStream = req.GetRequestStream())
                    {
                        var postData = Encoding.ASCII.GetBytes(requestBody);
                        req.ContentLength = postData.Length;
                        postStream.Write(postData, 0, postData.Length);
                    }
                }

                if (headers != null)
                {
                    if (headers.Keys.Any(p => p.ToLower() == "content-type"))
                        req.ContentType = headers.SingleOrDefault(p => p.Key.ToLower() == "content-type").Value;
                    if (headers.Keys.Any(p => p.ToLower() == "accept"))
                        req.Accept = headers.SingleOrDefault(p => p.Key.ToLower() == "accept").Value;
                }

                var response = (HttpWebResponse)req.GetResponse();

                using(Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
                    {
                        resuleJson = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(resuleJson);
        }

但是会发现,数据一直没有正常发送过去,而且代码还显得比较复杂

新的方式

这里修改一下写入 RequestStream 的方式,使用 StreamWriter 包装一下,然后直接写入需要发送的 Json 数据

private T PostDataViaHttpWebRequest<T>(string baseUrl,
            IReadOnlyDictionary<string, string> headers,
            IReadOnlyDictionary<string, string> urlParas,
            string requestBody=null)
        {
            var resuleJson = string.Empty;
            try
            {
                var apiUrl = baseUrl;

                if (urlParas != null)
                    urlParas.ForEach(p =>
                    {
                        if (apiUrl.IndexOf("{" + p.Key + "}") > -1)
                        {
                            apiUrl = apiUrl.Replace("{" + p.Key + "}", p.Value);
                        }
                        else
                        {
                            apiUrl += string.Format("{0}{1}={2}", apiUrl.Contains("?") ? "&" : "?", p.Key, p.Value);
                        }
                    }
                );
                
                var req = (HttpWebRequest)WebRequest.Create(apiUrl);
                req.Method = "POST";
                req.ContentType = "application/json"; //Defalt

                if (!requestBody.IsNullOrEmpty())
                {
                    using (var postStream = new StreamWriter(req.GetRequestStream()))
                    {
                        postStream.Write(requestBody);
                    }
                }

                if (headers != null)
                {
                    if (headers.Keys.Any(p => p.ToLower() == "content-type"))
                        req.ContentType = headers.SingleOrDefault(p => p.Key.ToLower() == "content-type").Value;
                    if (headers.Keys.Any(p => p.ToLower() == "accept"))
                        req.Accept = headers.SingleOrDefault(p => p.Key.ToLower() == "accept").Value;
                }

                var response = (HttpWebResponse)req.GetResponse();

                using(Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
                    {
                        resuleJson = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(resuleJson);
        }

这样即可正确发送 Json 数据。

到此这篇关于C#通过HttpWebRequest发送带有JSON Body的POST请求实现的文章就介绍到这了,更多相关C# post请求 HttpWebRequest内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

您可能感兴趣的文章:
  • C#发送Get、Post请求(带参数)
  • C#通过GET/POST方式发送Http请求
  • C#调用HTTP POST请求上传图片的示例代码
  • C#使用HttpPost请求调用WebService的方法
  • C#使用GET、POST请求获取结果
  • C#中后台post请求常用的两种方式总结

PostgreSQL PL / Python如何在性能方面与Python之外的Python进行比较?

PostgreSQL PL / Python如何在性能方面与Python之外的Python进行比较?

我运行完全相同的Python函数,一个作为Postgresql PL / Python,另一个作为通常的Python脚本在Postgresql之外运行.

令人惊讶的是,当我使用select * from pymax7(20000);调用Postgresql PL / Python时,它平均花费65秒,而当我调用通常的Python脚本python myscript.py 20000时,它平均需要48秒.计算运行查询和脚本10次的平均值.

是否应该有这样的差异? Postgresql RDBMS(PL / Python)中的Python如何在性能方面与Python之外的Python进行比较?

我在Ubuntu 12.04 64位上运行Postgresql 9.1和Python 2.7.

Postgresql PL / Python:

CREATE FUNCTION pymax7 (b integer)
  RETURNS float
AS $$   
  a = 0
  for i in range(b):
    for ii in range(b):
      a = (((i+ii)%100)*149819874987) 
  return a
$$LANGUAGE plpythonu;

Python:

import time
import sys

def pymax7 (b):     
    a = 0
    for i in range(b):
        for ii in range(b):
            a = (((i+ii)%100)*149819874987) # keeping Python busy
    return a

def main():    
    numIterations = int(sys.argv[1])        
    start = time.time()
    print pymax7(numIterations)
    end = time.time()
    print "Time elapsed in Python:"
    print str((end - start)*1000) + ' ms'        

if __name__ == "__main__":
    main()
最佳答案
应该没有任何区别.两个测试用例对我来说都有大约相同的运行时间,53秒加减1.

我确实调整了PL / Python测试用例,使用与普通Python测试用例相同的测量技术:

CREATE FUNCTION pymax7a (b integer)
  RETURNS float
AS $$
  import time
  start = time.time()
  a = 0
  for i in range(b):
    for ii in range(b):
      a = (((i+ii)%100)*149819874987)
  end = time.time()
  plpy.info("Time elapsed in Python: " + str((end - start)*1000) + ' ms')
  return a
$$LANGUAGE plpythonu;

这将告诉您是否涉及任何非Python开销. FWIW,对我来说,这个打印和客户端打印的psql与总时间之间的差异始终小于1毫秒.

今天关于Python发送带有标头的POSTpython post请求带headers的讲解已经结束,谢谢您的阅读,如果想了解更多关于.NET:发送带有数据的POST和读取响应的最简单方法、aiohttp 如何发送带有标头的请求、C#通过HttpWebRequest发送带有JSON Body的POST请求实现、PostgreSQL PL / Python如何在性能方面与Python之外的Python进行比较?的相关知识,请在本站搜索。

本文标签: