2009-06-26 192 views
2

我必須從android連接到web服務器,我必須從web服務器訪問web服務和網頁。有誰能夠幫助我?請使用一些代碼片段來逐步處理,因爲我是android新手,並且我不知道連接到Web服務器。使用android連接到web服務器

回答

0

你沒有提供非常多的信息(什麼樣的網頁,XML/JSON/HTML /等?)。但是常規Java的基本原則適用。使用URLInputStream

URL url = new URL(...); 
InputStream is = url.openStream(); 

從那裏它取決於你處理什麼樣的數據用。

+0

我訪問ASP網頁和Web服務 – Rajapandian 2009-06-26 07:26:09

1

您可以使用HttpClient

HttpClient httpClient = new DefaultHttpClient(); 
HttpGet httpGet = new HttpGet(uri); 
HttpResponse httpResponse = httpClient.execute(httpGet); 
BufferedReader reader = new BufferedReader(
    new InputStreamReader(httpResponse.getEntity().getContent())); 
// user reader to read & parse response 
reader.close();

解析響應顯然取決於格式(例如SOAPJSON等)

0

如果你不想使用額外的圖書館,這裏是發送一個「ID」和「名稱」到服務器的手段:


    URL url = null; 
    try { 
     String registrationUrl = String.format("http://myserver/register?id=%s&name=%s", myId, URLEncoder.encode(myName,"UTF-8")); 
     url = new URL(registrationUrl); 
     URLConnection connection = url.openConnection(); 
     HttpURLConnection httpConnection = (HttpURLConnection) connection; 
     int responseCode = httpConnection.getResponseCode(); 
     if (responseCode == HttpURLConnection.HTTP_OK) { 
      Log.d("MyApp", "Registration success"); 
     } else { 
      Log.w("MyApp", "Registration failed for: " + registrationUrl);    
     } 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 

您可以輕鬆地通過此發送其他數據URI「GET」風格,但如果您需要發送更詳細的信息,則需要POST。

注:原帖回答類似的問題在這裏:How to connect android to server