主要知识点:
- 获取的是inputStream字节流,在显示时,纯文本要先转换为字符流,其他的以字节流进行处理。
GET方式:
//path格式:http://网址?aaa=xxx&bbb=xxx
public InputStream getData(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
return is;
}
return null;
}
POST方式:
//path是网址,data格式为:aaa=xxx&bbb=xxx
public InputStream postData(String path,String data) throws Exception{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
//比GET方式多出来的设置
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);//post方式不能缓存
if (conn.getResponseCode() == 200) {
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
InputStream is = conn.getInputStream();
os.close();
return is;
}
return null;
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。