主要知识点:
- 获取的是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;
}