【发布时间】:2011-08-18 13:09:35
【问题描述】:
我有要转换的代码,以便从服务器以 GZIP 格式获取我的 xml。我不确定如何发送请求以查看是否接受编码以及不接受什么。这是一些代码:
public void parse(String locCode, int isMetric, String langId) throws IOException, ParserConfigurationException, SAXException {
//set member variables
this.locCode = locCode;
this.isMetric = isMetric;
this.langId = langId;
wdm.metric = isMetric;
try {
mCounter++;
//create input stream from url
InputStream is = getInputStream(this.locCode, this.isMetric, this.langId);
InputSource inputSource = new InputSource(is);
inputSource.setEncoding(ENCODING_TYPE);
//create sax parser and xml reader
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
mCounter = 0;
//pass in instance of FeedParser
xr.setContentHandler(new WeatherFeedParser());
xr.parse(inputSource);
is.close();
} catch (SocketException e){
if (mCounter < 3){
parse(locCode, isMetric, langId);
}
else e.printStackTrace();
} catch (UnknownHostException e){
if (mCounter < 3){
parse(locCode, isMetric, langId);
}
else e.printStackTrace();
}
}
private static final InputStream getInputStream(String locCode, int isMetric, String langId) throws IOException {
//build url
String addr = FEED_URL + LOCATION + cleanupInput(locCode) + "&" + METRIC + isMetric + "&" + LANG_ID + langId;
URL url = new URL(addr);
//create connection
mCon = url.openConnection();
mCon.setConnectTimeout((int)ACCUWX.Time._15_SECONDS);
mCon.setReadTimeout((int)ACCUWX.Time._15_SECONDS);
mCon.connect();
return mCon.getInputStream();
}
我已阅读其他帖子,但不确定我会在哪里使用此编码来实施建议:
HttpUriRequest request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip");
// ...
httpClient.execute(request);
Check response for content encoding:
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
【问题讨论】:
-
查看stackoverflow.com/questions/7139268/… 以获取使用
GzipDecompressingEntity的第二个代码示例的替代实现。