如何重构HttpURLConnection标头设置

时间:2014-10-23 05:22:13

标签: android refactoring httpurlconnection

每次我需要发送HttpURLConnection时,我需要设置很多属性 像这样:

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

问题是我有很多simliar设置。我该如何重构这些代码? 我不想查看很多相同的副本。

1 个答案:

答案 0 :(得分:0)

只需使用一个设置常量请求属性的方法,并将变量属性作为参数提供:

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