httpget + URI + Httpclient libraries discontinued. How to update code?

Asked

Viewed 117 times

1

I need to access the API Panoramio to fetch some images according to the sent coordinates.

However I am having trouble receiving the JSON value.

After several searches, all indicate code identical to this, but the libraries used are discontinued. It is possible to make a change to any other library?

Code:

    try {
        final URI uri = new URI("http", url, null);
        final HttpGet get = new HttpGet(uri);
        final HttpClient client = new DefaultHttpClient();
        final HttpResponse response = client.execute(get);
        final HttpEntity entity = response.getEntity();
        final String str = Utilities.convertStreamToString(entity.getContent());
        final JSONObject json = new JSONObject(str);
        parse(json);
    } catch (final Exception e) {
        Log.e(TAG, e.toString());
    }

My attempt at conversion:

     URL urll = new URL(endPoint);
     URLConnection connection = urll.openConnection();    
     InputStream inputStream = connection.getInputStream();

     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

     StringBuilder result = new StringBuilder();
     String line;

      while ((line = reader.readLine())!= null){

            result.append(line);
      }

      final String str = result.toString();
      final JSONObject json = new JSONObject(str);

Some help?

Thank you.

Original code

  • Yes, however I preferred the use of native Android libraries...

2 answers

1


You can use the class Scanner together with a stupid technique to use the delimiter \A to obtain all the contents of a data entry.

From the words of the author of the above article:

Remember that Scanner receives an entry from any class that implements Readable: InputStream, File, Chanel and so on. (...) Also remember that \A corresponds to the beginning of an input and since there is only one start in an input, Scanner goes all the flow at once.

import java.net.URL;
import java.util.Scanner;
import java.io.IOException;

public final class Test {

    private Test(){}

    public static final String getContentsFromUrl(URL url){
        String contents = "";
        try(Scanner scanner = new Scanner(url.openStream()).useDelimiter("\\A")){
            if(scanner.hasNext())
                contents = scanner.next();
        } catch(IOException ex){
            // seja legal e trate as exceções :)
        }   
        return contents;
    }
}

And to use:

String data = Test.getContentsFromUrl(new URL("http://foo.com/json"));
if(!data.isEmpty()){
  // otimitindo try/catch para criar o JSONObject
  JSONObject json = new JSONObject(data);
}

1

You can use the library okhttp to download json, which extremely easy its implementation and many "big" applications use it such as Spotify and Duo.

To add to your project simply add the following line to your build.Radle dependencies

compile 'com.squareup.okhttp3:okhttp:3.4.1'

follows an example of its use:

public String getDadosServer(){
    OkHttpClient client = new OkHttpClient();

    String run(String url) throws IOException {
      Request request = new Request.Builder()
          .url(url)
          .build();

      Response response = client.newCall(request).execute();
      return response.body().string();
    }

To convert the received Json into object there are several libraries like Gson which was made by Google, there is also the Jackson, but both involve Reflection, and in java, more specifically on Android, Reflection is an extremely slow feature.. So I recommend it to Logansquare, that generates a code during the compilation of the project, optimizing the execution of the project.

To add to your project some rules should be followed: In your build.Radle add the following:

 buildscript {
        repositories {
            jcenter()
        }
        dependencies {
            classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        }
    }
    apply plugin: 'com.neenbedankt.android-apt' //este plugin será responsável por gerar o código durante a compilacao

    dependencies {
        apt 'com.bluelinelabs:logansquare-compiler:1.3.6'
        compile 'com.bluelinelabs:logansquare:1.3.6'
    }

and in your project you need to create a class that represents the received json to make the automatic conversion from JSON to the object..

Follow an example...

@JsonObject
public class SeuObjeto{

    @JsonField
    public String format;


    @JsonField(name = "_id")
    public int imageId;

    @JsonField
    public String url;

    @JsonField
    public String description;
}

and after you have made the query and have the JSON in its variable just call the Logansquare.

SeuObjeto obj = LoganSquare.parse(strJSON, SeuObjeto.class);

I hope I’ve helped..

  • Thank you very much for the answer, but as it is for academic purposes I would like to use native libraries, however otherwise I will definitely consult... And of course I have my +1 for availability...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.