Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is the code I have written to develop an android application which sends a request to the webserver and to parse JSON objects: 

public JSONObject RequestWithHttpUrlConn(String _url, String param){

    HttpURLConnection con = null;

    URL url;

    String response = "";

    Scanner inStream = null;

    PrintWriter out = null;

    try {

        url = new URL(_url);

        con = (HttpURLConnection) url.openConnection();

        con.setDoOutput(true);

        con.setRequestMethod("POST");

        if(param != null){

            con.setFixedLengthStreamingMode(param.getBytes().length);

        }

        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        out = new PrintWriter(con.getOutputStream());

        if(param != null){

            out.print(param);

        }

        out.flush();

        out.close();

        inStream = new Scanner(con.getInputStream());

        while(inStream.hasNextLine()){

            response+=(inStream.nextLine());

        }

    } catch (MalformedURLException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } catch (IOException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } finally{

        if(con != null){

            con.disconnect();

        }if(inStream != null){

            inStream.close();

        }if(out != null){

            out.flush();

            out.close();

        }

    }

}

When I run the above code, I get the following error:

“java.net.SocketTimeoutException: Connection timed out”. Can anyone tell me what am I doing wrong here?

1 Answer

0 votes
by (19.7k points)

If you are getting a ‘connection timeout’, an effective way to handle it is to use a try-catch block. Check the below code: 

HttpUrlConnection conn = (HttpURLConnection) url.openConnection();

//set the timeout in milliseconds

conn.setConnectTimeout(7000);

Interested in Java? Check out this Java tutorial by Intellipaat. 

Browse Categories

...