如何模拟 HttpURLConnection 中的 getContent() 方法,在示例代码中,还有如何从模拟 URL 获取响应。
public class WebClient {
public String getContent(URL url) {
StringBuffer content = new StringBuffer();
try {
HttpURLConnection connection = createHttpURLConnection(url);
connection.setDoInput(true);
InputStream is = connection.getInputStream();
int count;
while (-1 != (count = is.read())) {
content.append(new String(Character.toChars(count)));
}
} catch (IOException e) {
return null;
}
return content.toString();
}
protected HttpURLConnection createHttpURLConnection(URL url) throws IOException{
return (HttpURLConnection)url.openConnection();
}
}
谢谢