【问题标题】:How to perform HTTP GET operation in Python? [closed]如何在 Python 中执行 HTTP GET 操作? [关闭]
【发布时间】:2013-04-10 00:46:37
【问题描述】:

我希望我的代码将“请求 url”作为输入,并将输出作为“响应 XML”。这是我想用python来实现的。我不知道如何,因为我是 python 新手。虽然我知道如何在 Java 中做到这一点,并且为此我已经用 Java 开发了代码。因此,如果有人可以帮助我解决这个问题。

Java 代码 sn-p:

import java.net.*;    // import java packages.  
import java.io.*;
import java.net.URL;

public class API {
    public static void main(String[] args) throws Exception {
URL API = new URL("http:server//"); // Create a URL object 'API' that will locate the resources on remote server via HTTP protocol.
        URLConnection request = API.openConnection(); // Retrieve a URLConnection object 'request' that will establish http connection by using openConnection() method.
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    request.getInputStream())); // Create an Output stream ‘in’ that will call InputStreamReader to read the contents of the resources.
        String response;
        while ((response = in.readLine()) != null) // Write to Output stream until null.
            System.out.println(response); // prints the response on Console.
        in.close(); // Close Output stream.
    }
}

【问题讨论】:

    标签: python


    【解决方案1】:
    from socket import *
    s = socket()
    s.connect(('example.com', 80))
    s.send('GET / HTTP/1.1\r\n\r\n')
    print s.recv(8192)
    

    ?

    或者:http://docs.python.org/2/library/urllib2.html

    import urllib2
    f = urllib2.urlopen('http://www.python.org/')
    print f.read(100)
    



    第一个选项可能需要更多的标题项,例如:

    from socket import *
    s = socket()
    s.connect(('example.com', 80))
    s.send('GET / HTTP/1.1\r\nHost: example.com\r\nUser-Agent: MyScript\r\n\r\n')
    print s.recv(8192)
    

    另外,我倾向于第一个解决方案(因为,你做你想做的事,别无其他)要求你对 HTTP 协议有基本的了解。

    例如,这是 HTTP 协议对 GET 请求的工作方式:

    GET <url> HTTP/1.1<cr+lf>
    <header-key>: <value><cr+lf>
    <cr+lf>
    

    这里有更多信息,例如:http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Client_request

    【讨论】:

    • 你能告诉我 100 是什么意思 in line print f.read(100) 吗?感谢您提供解决方案。
    • 读取前 100 个字符。从某种意义上说,它基本上是一个“文件”运算符。摆弄它并尝试一些东西,我认为您可以在没有任何参数的情况下只使用.read(),这将获取所有数据。
    • 是的,我试过 .read() 它正在从服务器获取所有数据。谢谢。
    • 我也用这个方法,但是在recv之前设置s.settimeout(5.0),以免陷入死循环。
    【解决方案2】:

    还有一个名为requests 的不错的包,它使您在 Python 中的 http 需求变得更加容易。

    对于获取请求,您会这样做:

    r = requests.get('http://www.example.com')
    print(r.text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      相关资源
      最近更新 更多