Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Networking: getting third party API OkHTTP (synchronous get: https://github.com/square/okhttp/wiki/Recipes)
- MainActivity.java
- package com.teamtreehouse.stormy;
- import android.support.v7.app.ActionBarActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.Menu;
- import android.view.MenuItem;
- import com.squareup.okhttp.Call;
- import com.squareup.okhttp.OkHttpClient;
- import com.squareup.okhttp.Request;
- import com.squareup.okhttp.Response;
- import java.io.IOException;
- public class MainActivity extends ActionBarActivity {
- public static final String TAG= MainActivity.class.getSimpleName();
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- String apiKey = "d5faf0cb201f103df4dde0b8b0a4f490";
- double latitude = 37.8267;
- double longitude = -122.423;
- String forecastUrl = "https://api.forecast.io/forecast/d5faf0cb201f103df4dde0b8b0a4f490/," + apiKey +
- "/" + latitude +"/" + "," + longitude; //Concatenate the parameters
- //Recipe from OkHTTP github https://github.com/square/okhttp/wiki/Recipes
- OkHttpClient client = new OkHttpClient(); // we want to build an HTTP request using OkHttp. Create a new 'OkHttpClient' variable and initialize it using the default constructor.
- // Build a request that the client will send to the server (Forecast.io). Simple:
- Request request = new Request.Builder().url(forecastUrl).build(); // alt+enter then select import OkHTTP version of request //
- /* Can also be formatted this way (drop to the next line for readability
- Request request = new Request.Builder()
- .url(forecastUrl)
- .build();
- */
- /* example used in challenge:
- Next we need to create and build a Request. Declare a new Request variable,
- and then set it by chaining a few methods together.
- First use new Request.Builder(), then chain the url() method using apiUrl as the parameter.
- Then chain build() to finish.
- Request request = new Request.Builder().url(apiUrl).build();
- */
- // And the next thing we need is a Call object, we're going to put this request inside a Call object.
- // So, the data type is call, we'll name it call.
- Call call = client.newCall(request);
- // execute the call:
- try {
- //We have an execute method from our call class, and it returns a response object.
- //So let's store that response in a variable:
- Response response = call.execute();
- //add this //now we want to check if the request is successful (there is a handy method from the response class):
- if (response.isSuccessful()){
- Log.v(TAG, response.body().string());//Log entire response body
- }
- } catch (IOException e) {
- Log.e(TAG, "Exception caught: ", e);
- }
- }
- }
- // https://github.com/square/okhttp/wiki/Recipes
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement