Cody Blog

Send HTTP Request in Android

In the most of time, you could just use HTTP library like Volley or OkHTTP. If you want to use native Android function call for some reasons, you should use HttpURLConnection. HttpClient has been deprecated since Android 6.0(sdk 23).

For HttpURLConnection , there is an excellent code snippet on here

Note: Android don't allow network request happened on main UI thread. If you did this, a android.os.NetworkOnMainThreadException exception will be thrown out. Put them in AsyncTask or Service instead.

Build Url:

Uri.Builder builder = Uri.parse(FORECAST_BASE_URL).buildUpon();
urlBuilder.scheme("http");
urlBuilder.authority("api.openweathermap.org");
urlBuilder.appendEncodedPath("data/2.5/forecast/daily");
urlBuilder.appendQueryParameter("zip", zip);
urlBuilder.appendQueryParameter("mode", "json");
urlBuilder.appendQueryParameter("units", "metric");
urlBuilder.appendQueryParameter("cnt", Integer.toString(numberOfDays));
urlBuilder.appendQueryParameter("appid", BuildConfig.OPENWEATHER_API_KEY);

Use this url object to send http request and get json response back:

String resultString = null;
URL url = new URL(urlString);

// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();

// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
    // Nothing to do.
    forecastJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));

String line;
while ((line = reader.readLine()) != null) {
    buffer.append(line);
}

if (buffer.length() == 0) {
    // Stream was empty.  No point in parsing.
    forecastJsonStr = null;
}
resultString = buffer.toString();

Reference

Android

Related Posts

Comments