使用android连接到web服务器

使用android连接到web服务器

问题描述:

我必须从android连接到web服务器,我必须从web服务器访问web服务和网页。有谁能够帮助我?请使用一些代码片段来逐步处理,因为我是android新手,并且我不知道连接到Web服务器。使用android连接到web服务器

你没有提供非常多的信息(什么样的网页,XML/JSON/HTML /等?)。但是常规Java的基本原则适用。使用URLInputStream

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

从那里它取决于你处理什么样的数据用。

+0

我访问ASP网页和Web服务 – Rajapandian 2009-06-26 07:26:09

您可以使用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等)

如果你不想使用额外的图书馆,这里是发送一个“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