describe HTTP requests • Framework to interact with APIs and sending network requests • Automatically parses downloaded data into a Plain Old Java Object
> { public static final String REQUEST_METHOD = "GET"; public static final int READ_TIMEOUT = 15000; public static final int CONNECTION_TIMEOUT = 15000; @Override protected String doInBackground(String...params) { String stringUrl = params[0]; String result; String inputLine; try { //Create a URL object holding our url URL myUrl = new URL(stringUrl); //Create a connection HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection(); //Set methods and timeouts connection.setRequestMethod(REQUEST_METHOD); connection.setReadTimeout(READ_TIMEOUT); connection.setConnectTimeout(CONNECTION_TIMEOUT); //Connect to our url connection.connect() //Create a new InputStreamReader InputStreamReader streamReader = new InputStreamReader(connection.getInputStream()); //Create a new buffered reader and String Builder BufferedReader reader = new BufferedReader(streamReader); StringBuilder stringBuilder = new StringBuilder(); //Check if the line we are reading is not null while ((inputLine = reader.readLine()) != null) { stringBuilder.append(inputLine); } //Close our InputStream and Buffered reader reader.close(); streamReader.close(); //Set our result equal to our stringBuilder result = stringBuilder.toString(); } catch (IOException e) { e.printStackTrace(); result = null; } return result; } protected void onPostExecute(String result) { super.onPostExecute(result); } } Now imagine making many network calls at the same time!
define URLs to hit ◦ JSON Parsing is all done for you • Supports async requests with minimal code ◦ NO MORE ASYNCTASKS + Manual Json parsing • Great Documentation and Community
HTTP request within Retrofit • More efficient than standard Java I/O library for reading and writing data • Works best with a single instance across application ◦ Each new instance gets its own private connection pool ◦ Creating many will prevent connection reuse ◦ Each connection pool holds its own set of connections alive ◦ Too many connection pools will exhaust memory
Retrofit.Builder() .baseUrl("https://api.github.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); GitHubService service = retrofit.create(GitHubService.class); Specify the base URL Add the JSON converter Implement the service