【问题标题】:Restful webservice in Android [duplicate]Android中的Restful Web服务[重复]
【发布时间】:2016-03-11 19:37:52
【问题描述】:

我想访问一个 Web 服务函数,该函数接受两个字符串作为参数并返回一个 JSON 值。我找到了使用 volley 库执行此操作的解决方案,但显然我必须为此使用 Android Lolipop。 没有凌空抽射有没有办法做到这一点?另一个图书馆?还是httpconnection? 这种用法的一个例子将是完美的。

【问题讨论】:

  • 我强烈推荐使用 RxJava 改造 rest 客户端库。在性能、执行时间、可观察性和许多其他方面,这是最有效的方式。看看他们。

标签: java android web-services rest


【解决方案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
    }
}

【讨论】:

    猜你喜欢
    • 2012-01-12
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    相关资源
    最近更新 更多