Search code examples
androidapachehttpclienthttpurlconnectiongoogle-url-shortener

How to use the new URLConnection for Urlshortner in android


i am trying to change HTTPClient deprecated code but i get i/o exception always and i dont know where i am wrong. my old deprecated code snippt

  public JSONObject getJSONFromUrl(String address, String longUrl) {
     // Making HTTP request
     try {
        // DefaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(address);

        httpPost.setEntity(new StringEntity("{\"longUrl\":\"" + longUrl + "\"}"));
        httpPost.setHeader("Content-Type", "application/json");
        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

my new not working code snippt

 try {
    HttpURLConnection httpcon = (HttpURLConnection) ((new          URL(address).openConnection()));
    httpcon.setDoOutput(true);
    httpcon.setRequestProperty("Content-Type", "application/json");
    httpcon.setRequestMethod("POST");
    httpcon.connect();

 //   byte[] outputBytes = "{'value': 7.5}".getBytes("UTF-8");
   is = httpcon.getInputStream();
 /*   os.write(outputBytes);

    os.close();*/
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    catch (Exception e) {
        e.printStackTrace();
    }

Solution

  • First you need to send your parameter value to the URL, which you are not sending yet.

     OutputStream out = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
                writer.write(--SENDING PARAMETER HERE--);
                writer.flush();
                writer.close();
                out.close();
    

    Then next, use bufferedReader to get response:

    BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream(), "UTF-8"));
    

    And receive the response as follows:

    while ((inputLine = in.readLine()) != null) 
    {
        Log.d("finalResponse: ", inputLine);
    }
    

    Set the inputLine data type to the data type of your response. Make sure the parameter you are sending is exactly in the form the API/URL is set up to receive it as.

    And yes, don't forget to close the BufferedReading and disconnect URLConnection.

    in.close();
    httpcon.disconnect();
    

    I hope this helps. Happy Coding.