Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. try {
  2.  
  3. URL url = new URL(baseURL+ "/sortbyname");
  4. HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  5.  
  6. //sortbyname: 2-name
  7. JSONObject jsonParam = new JSONObject();
  8. jsonParam.put("username", params[1]);
  9.  
  10. urlConnection.setDoOutput(true);
  11. urlConnection.setRequestProperty("Content-Type", "application/json");
  12. urlConnection.setRequestMethod("POST");
  13. urlConnection.connect();
  14.  
  15. DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
  16. wr.writeBytes(jsonParam.toString());
  17. wr.flush();
  18. wr.close();
  19.  
  20. int response_code = urlConnection.getResponseCode();
  21.  
  22. // Check if successful connection made
  23. if (response_code == HttpURLConnection.HTTP_OK) {
  24.  
  25. // Read data sent from server
  26. InputStream input = urlConnection.getInputStream();
  27. BufferedReader reader = new BufferedReader(new InputStreamReader(input));
  28. StringBuilder result = new StringBuilder();
  29. String line;
  30.  
  31. while ((line = reader.readLine()) != null) {
  32. result.append(line);
  33. }
  34.  
  35. // Parse JSON object and return it
  36. JSONObject obj = new JSONObject(result.toString());
  37. if(obj.getString("success").equals("false")){
  38. return (obj.getString("errormsg").toString());
  39. }
  40. else {
  41. JSONArray arr = obj.getJSONArray("users");
  42. int length = arr.length();
  43. if(length == 0){
  44. return "empty";
  45. }
  46. String usernames_list = "";
  47. for(int i = 0; i<length; i++){
  48. String username = arr.getJSONObject(i).getString("name");
  49. usernames_list = usernames_list + username + ",";
  50. }
  51. return usernames_list;
  52. }
  53. } else {
  54.  
  55. return ("unsuccessful");
  56. }
  57.  
  58. } catch (MalformedURLException e) {
  59. e.printStackTrace();
  60. } catch (IOException e) {
  61. e.printStackTrace();
  62. } catch (JSONException e) {
  63. e.printStackTrace();
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement