2014-03-24 164 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。 –

相关问题