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

// 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) {

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



Related Posts