Java Android中的Restful Web服务
我想访问一个webservice函数,该函数以两个字符串作为参数并返回一个JSON值。我用截击库找到了一个解决方案,但显然我必须使用Android Lolipop。 有没有一种不用截击的方法?另一个图书馆?还是httpconnection? 这种用法的一个例子将是完美的。您可以使用库 或者使用httpURLConnectionJava Android中的Restful Web服务,java,android,web-services,rest,Java,Android,Web Services,Rest,我想访问一个webservice函数,该函数以两个字符串作为参数并返回一个JSON值。我用截击库找到了一个解决方案,但显然我必须使用Android Lolipop。 有没有一种不用截击的方法?另一个图书馆?还是httpconnection? 这种用法的一个例子将是完美的。您可以使用库 或者使用httpURLConnection HttpURLConnection httpURLConnection = null; try { // create URL URL url =
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
}
}
我强烈建议用RxJava改造rest客户机库。就性能、执行时间、可观察性和许多其他方面而言,这是最有效的方法。看看他们。