URL验证工作正常,但保持连接并限制任何进一步的请求

时间:2012-11-20 10:34:38

标签: android http http-headers url-validation

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);
    }

}

我使用上面的dode来验证网址,

如果HEAD给我回复代码200,那么我只打开webview的网址。

但是一旦我调用它就保持连接,即使关闭后也不允许任何其他http请求,该怎么办?

Safe use of HttpURLConnection

2 个答案:

答案 0 :(得分:4)

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

这是因为HttpURLConnection使连接保持活动状态,因此我们无法进行进一步的请求,因此保持活动设置为false可以解决此问题。

答案 1 :(得分:1)

要正确关闭HttpURLConnection,请转到link

此网址已关闭。