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

1

I need to access the Panoramio API to get some images based on the coordinates I've sent.

However, I'm having trouble receiving the JSON value.

After several searches, all indicate identical code, but the libraries used are discontinued. Is it possible to make a change to another 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 conversion attempt:

     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);

Any help?

Thank you.

Original Code

    
asked by anonymous 02.09.2016 / 20:34

2 answers

1

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

From the words of the author of the article above:

  

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

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);
}
    
02.09.2016 / 22:36
1

You can use the okhttp library to download json, which is extremely easy to implement and many " use it like Spotify and Duo.

To add to your project simply add the following line in the dependencies of your build.gradle

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

Here's an example of using it:

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 an object there are several libraries like Gson that was made by Google, there is also Jackson , but both involve reflection, and in Java, more specifically in Android, reflection is an extremely slow feature .. So I recommend the LoganSquare , which generates a code during the compilation of the project, optimizing its execution.

To add in your project some rules should be followed: In your build.gradle 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'
    }

In your project you need to create a class that represents the json received to do the automatic JSON conversion to the object.

Here's an example ...

@JsonObject
public class SeuObjeto{

    @JsonField
    public String format;


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

    @JsonField
    public String url;

    @JsonField
    public String description;
}

After you have made the query and you have JSON in your variable, just call LoganSquare.

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

I hope I have helped ..

    
02.09.2016 / 20:55