Android 中的 Restful Web 服务 [英] Restful webservice in Android
本文介绍了Android 中的 Restful Web 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想访问一个 webservice 函数,它接受两个字符串作为参数并返回一个 JSON 值.我找到了使用 volley 库执行此操作的解决方案,但显然我必须为此使用 Android Lolipop.有没有办法在没有凌空抽射的情况下做到这一点?另一个图书馆?或httpconnection?这种用法的一个例子将是完美的.
I want to access a webservice function that takes two strings as arguments and return a JSON value. I found a solution to do this using volley library but apparently i have to use Android Lolipop for this. is there a way to do this without volley? Another library? or httpconnection? An example of this use will be perfect.
推荐答案
你可以使用一个库 http://square.github.io/retrofit/
或使用 httpURLConnection
or using 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
}
}
这篇关于Android 中的 Restful Web 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文