2014-03-24 139 views
0

我正在構建一個android應用程序,我需要使用Web服務將數據發送到它並返回一個字符串。爲了達到這個目的,我創建了一個AsyncTask來完成後臺任務。使用java返回來自Web服務的響應數據

protected String doInBackground(Void... params) { 
      URL postUrl; 
      try { 
       postUrl = new URL("http://192.168.2.102/Rest%20Service/index.php"); 
      } catch (MalformedURLException e) { 
       throw new IllegalArgumentException("invalid url"); 
      } 

      String body = "mdxEmail=" + email + "&mdxPassword="+ password; 

      byte[] bytes = body.getBytes(); 
      String response = null; 
      HttpURLConnection conn = null; 
      try { 
       conn = (HttpURLConnection) postUrl.openConnection(); 
       conn.setDoOutput(true); 
       conn.setUseCaches(false); 
       conn.setFixedLengthStreamingMode(bytes.length); 
       conn.setRequestMethod("POST"); 
       conn.setRequestProperty("Content-Type", 
         "application/x-www-form-urlencoded;charset=UTF-8"); 
       // post the request 
       OutputStream out = conn.getOutputStream(); 
       out.write(bytes); 
       out.close(); 
       // handle the response 
       int status = conn.getResponseCode(); 
       if (status != 200) { 
        throw new IOException("Post failed with error code " + status); 
       } 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } finally { 
       if (conn != null) { 
        conn.disconnect(); 
       } 
      } 
      return response; 
     } 

我的問題是我如何獲得從Web服務返回的數據?

+1

請參閱本[鏈接](http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ )..它會幫助你 – Akshay

回答

0

一旦發佈,你可以得到這樣返回的數據:

BufferedReader in = new BufferedReader(
      new InputStreamReader(conn.getInputStream())); 
    String inputLine; 
    StringBuffer response = new StringBuffer(); 

    while ((inputLine = in.readLine()) != null) { 
     response.append(inputLine); 
    } 
    in.close(); 
+0

我試過這個,但由於某種原因'inputLine'返回null。 –

相關問題