2013-04-17 47 views
-5

我希望我的代碼將「請求URL」作爲輸入並將輸出作爲「響應XML」。這我想用python來實現。我不知道如何,因爲我是新來的python。雖然我知道如何在Java中完成此任務,爲此我已經開發了Java代碼。所以如果有人能幫助我。如何在Python中執行HTTP GET操作?

Java代碼片斷:

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. 
    } 
} 

回答

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

+0

你能告訴我這是什麼排隊打印f.read 100個單元(100)?感謝您提供解決方案。 –

+0

它讀取前100個字符。基本上這是一個「文件」操作符。擺弄它並嘗試一些東西,我認爲你可以只用'.read()'而不用任何參數,並且可以獲取所有數據。 – Torxed

+0

是的,我試過.read()它是從服務器獲取所有數據。謝謝。 –

1

還有一個好的包requests,使你的HTTP Python中的需求要容易得多。

對於GET請求,你會怎麼做:

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