我想访问一个webservice函数,它接受两个字符串作为参数并返回一个JSON值。我找到了使用排球库来做到这一点的解决方案,但显然我必须使用Android Lolipop。 有没有办法在没有凌空的情况下做到这一点?另一个库?还是httpconnection? 这种用法的一个例子是完美的。
答案 0 :(得分: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
}
}