Search code examples
androidhttphttp-headersurl-validation

URL validation works fine but keep connection and restrict any further requests


public class UrlVarificationTask extends AsyncTask<Void, Void, Integer> {

    private String url;
    private UrlVarificationDelegate delegate;
    private HttpURLConnection huc;

    public UrlVarificationTask(String url, UrlVarificationDelegate delegate) {
        this.url = url;
        this.delegate = delegate;
    }

    @Override
    protected void onPreExecute() {

        super.onPreExecute();
    }

    @Override
    protected Integer doInBackground(Void... params) {
        int responseCode = 0;
        try {
            System.setProperty("http.keepAlive", "false");
            URL u = new URL(url);
            huc = (HttpURLConnection) u.openConnection();
            huc.setRequestMethod("HEAD");
            huc.connect();
            responseCode = huc.getResponseCode();

        } catch (MalformedURLException mal) {
            responseCode = -555;
        } catch (IOException io) {
            responseCode = -444;
        } catch (Exception ex) {
            responseCode = -333;
            ex.printStackTrace();
        }

        if (huc != null) {
            try {
                huc.getInputStream().close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            huc.disconnect();
        }

        Logger.debug("Response Code==" + responseCode);
        return responseCode;
    }

    @Override
    protected void onPostExecute(Integer responseCode) {
        delegate.urlVarificationResponseCode(responseCode);
        super.onPostExecute(responseCode);
    }

}

I used above dode for validating url,

if HEAD give me response code 200 then only I open a url to webview.

but once I call this it keep connection and not allow any other http request even after close, what to do ?

Safe use of HttpURLConnection


Solution

  • huc.setRequestProperty("keep-alive", "false");
    

    this is working as HttpURLConnection keep connection alive and hence we cann't make make further request so keep-alive setting to false resolve this problem.