主要知識點:
- 獲取的是inputStream字節(jié)流,在顯示時控汉,純文本要先轉(zhuǎn)換為字符流笔诵,其他的以字節(jié)流進(jìn)行處理。
GET方式:
//path格式:http://網(wǎng)址?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是網(wǎng)址姑子,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方式多出來的設(shè)置
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;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者