HttpURLConnection GET和POST获取文本数据¶
AndroidManifest.xml
中不要忘记申请网络权限
GET方式获取文本数据¶
目标网址是 https://www.baidu.com/s?wd=abc ,这是百度搜索abc
新建URL对象后,调用openConnection()
方法建立连接,得到HttpURLConnection
。设置一些参数。
然后从HttpURLConnection
连接中获取输入流,从中读取数据。
try {
URL url = new URL("https://www.baidu.com/s?wd=abc");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);
conn.setRequestProperty("Cache-Control", "max-age=0");
conn.setDoOutput(true);
int code = conn.getResponseCode();
if (code == 200) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream inputStream = conn.getInputStream();
byte[] in = new byte[1024];
int len;
while ((len = inputStream.read(in)) > -1) {
baos.write(in, 0, len);
}
final String content = new String(baos.toByteArray());
baos.close();
inputStream.close();
conn.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
POST调用接口¶
和上文的GET类似,都是url开启连接拿到conn
,然后设置参数。
这里我们用POST方法,并且带有body
。服务器能收到我们传上去的参数。
假设服务器接受的是json格式。
try {
URL url = new URL("http://sample.com/sample");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(10 * 1000);
// 这里是示例
JSONObject bodyJson = new JSONObject();
bodyJson.put("imei", "获取imei");
bodyJson.put("deviceSn", "获取sn");
bodyJson.put("deviceBrand", Build.BRAND);
String body = bodyJson.toString();
conn.setRequestProperty("Content-Type", "application/json"); // 类型设置
conn.setRequestProperty("Cache-Control", "max-age=0");
conn.setDoOutput(true);
conn.getOutputStream().write(body.getBytes());
int code = conn.getResponseCode();
if (code == 200) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream inputStream = conn.getInputStream();
byte[] in = new byte[1024];
int len;
while ((len = inputStream.read(in)) > -1) {
baos.write(in, 0, len);
}
String content = new String(baos.toByteArray());
baos.close();
inputStream.close();
conn.disconnect();
JSONObject jsonObject = new JSONObject(content);
// 根据定义好的数据结构解析出想要的东西
}
} catch (Exception e) {
e.printStackTrace();
}
实际开发中,我们会使用一些比较成熟的网络框架,例如OkHttp。
作者: rustfisher.com | rf.cs@foxmail.com
示例: AndroidTutorial Gitee, Tutorial Github
本文链接: https://www.an.rustfisher.com/android/network/URLConnection/HttpURLConnection_get_post/
一家之言,仅当抛砖引玉。如有错漏,还请指出。如果喜欢本站的内容,还请支持作者。也可点击1次下方的链接(链接内容与本站无关),谢谢支持服务器。
如有疑问,请与我联系:Android issues - gitee