Restful webservice in Android [duplicate]

↘锁芯ラ 提交于 2019-12-26 06:09:17

问题


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.


回答1:


You can use a library http://square.github.io/retrofit/

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
    }
}


来源:https://stackoverflow.com/questions/35948522/restful-webservice-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!