问题描述:

Everytime I need to send an HttpURLConnection, I need to set lots of properties

like this:

conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(ConnectStateVar.connExpireTime);

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

conn.setRequestProperty("Cache-Control", "max-age=0");

conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");

conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");

conn.setRequestProperty("Charset", "UTF-8");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setDoOutput(false);

conn.setDoInput(true);

conn.setRequestMethod("GET");

The question is that I have lots of simliar settings. How should I refactor these code?

I don't want to view lots of same copies.

网友答案:

Simply use a method that sets the constant request properties and provide the variable properties as arguments:

void initConnection(URLConnection conn, String contentType, ... <other variable headers as arguments>) {
    // set the constant header values
    conn.setRequestProperty("Cache-Control", "max-age=0");
    conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/       xml;q=0.9,image/webp,*/*;q=0.8");
    conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
    conn.setRequestProperty("Charset", "UTF-8");
    conn.setRequestProperty("Connection", "Keep-Alive");

    //set the variable headers passed as arguments. For example ContentType
    conn.setRequestProperty("Content-Type", contentType);
}
相关阅读:
Top