com.mitchtodd.myweatherapp.webservices.MyWeather2Service.java Source code

Java tutorial

Introduction

Here is the source code for com.mitchtodd.myweatherapp.webservices.MyWeather2Service.java

Source

/*
 * Copyright (C) 2014 The Android Open Source Project 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package com.mitchtodd.myweatherapp.webservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.mitchtodd.myweatherapp.data.Weather;

/*
 * MyWeather2.com web service client (see http://www.myweather2.com/developer/).
 */
public class MyWeather2Service {
    private static final String SERVICE_URL = "http://www.myweather2.com/developer/forecast.ashx?"; // base url
    private static final String SERVICE_UAC = "KDrRbvwbAt"; // unique client access code
    private static final String SERVICE_REQUEST_FORMAT = "json"; // hard-coded request format
    private static final String SERVICE_REQUEST_TEMPUNITS = "f"; // hard-coded request units for temperature (TODO: add as user preference)
    private static final String SERVICE_REQUEST_SPEEDUNITS = "mph"; // hard-coded request units for speed (TODO: add as user preference)

    /*
     * Construct new instance of MyWeather2Service.
     */
    public MyWeather2Service() {

    }

    /*
     * Generate HTTP request, receive response as json formatted string, and create/return Weather instance.
     */
    public Weather requestWeather(String zipCode) {
        Weather weather = null;

        StringBuilder builder = new StringBuilder();
        int timeoutConnection = 5000;
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpClient client = new DefaultHttpClient(httpParameters);
        String requestUrl = createRequestUrl(zipCode);
        HttpGet httpGet = new HttpGet(requestUrl);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
                weather = new Weather(builder.toString());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return weather;
    }

    private String createRequestUrl(String zipCode) {
        StringBuilder builder = new StringBuilder();
        builder.append(SERVICE_URL);
        builder.append("uac=");
        builder.append(SERVICE_UAC);
        builder.append("&output=");
        builder.append(SERVICE_REQUEST_FORMAT);
        builder.append("&temp_unit=");
        builder.append(SERVICE_REQUEST_TEMPUNITS);
        builder.append("&ws_unit=");
        builder.append(SERVICE_REQUEST_SPEEDUNITS);
        builder.append("&query=");
        builder.append(zipCode);
        return builder.toString();
    }

}