2016-03-11 67 views
-1

我想访问一个webservice函数,它以两个字符串作为参数并返回一个JSON值。我发现一个解决方案,使用排球库,但显然我必须使用Android Lolipop。 有没有办法做到这一点没有齐射?另一个库?或httpconnection? 这种使用的例子将是完美的。Android中的Restful webservice

+1

我会强烈建议改造REST客户端库,具有RxJava。这是在性能,执行时间,可观察等诸多方面最有效的方式。去看一下。 –

回答

1

您可以使用图书馆http://square.github.io/retrofit/

或使用HttpURLConnection的

HttpURLConnection httpURLConnection = null; 
try { 
    // create URL 
    URL url = new URL("http://example.com"); 
    // open connection 
    httpURLConnection = (HttpURLConnection) url.openConnection(); 
    httpURLConnection.setRequestMethod("GET"); 
    // 15 seconds 
    httpURLConnection.setConnectTimeout(15000); 
    Uri.Builder builder = new Uri.Builder().appendQueryParameter("firstParameter", firsParametersValue).appendQueryParameter("secondParameter", secondParametersValue) 
    String query = builder.build().getEncodedQuery(); 
    OutputStream outputStream = httpURLConnection.getOutputStream(); 
    BufferedWriter bufWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); 
    bufWriter.write(query); 
    bufWriter.flush(); 
    bufWriter.close(); 
    outputStream.close(); 

    if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
     StringBuilder response = new StringBuilder(); 
     BufferedReader input = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()), 8192); 
     String strLine = null; 
     while ((strLine = input.readLine()) != null) { 
      response.append(strLine); 
     } 
     input.close(); 
     Object dataReturnedFromServer = new JSONTokener(response.toString()).nextValue(); 
     // do something 
     // with this 
    } 
} catch (Exception e) { 
    // do something 
} finally { 
    if (httpURLConnection != null) {   
     httpURLConnection.disconnect();// close connection 
    } 
}