Andoid网络请求是Android程序开发当中使用相当频繁的,Android中的http请求分为get、post两种方式:
方法一:使用httpUrlconnection请求服务
大致流程:
1.创建一个url对象
2.创建一个连接的对象
3.设置请求连接的配置信息
4.获取请求的返回码
5.获取请求的流信息
6.解析请求的流信息
①GET 方式 get方式也可以传参 ,只不过参数是要拼接在url后面的
例如:http://xuhaiyang-pc:8080/itheima72/servlet/LoginServlet?username=aaa&pwd=aaaa
1.URL url = new URL(path);
2.HttpURLConnection conn = (HttpURLConnection) url.openConnection();
3. conn.setRequestMethod("GET");
conn.setReadTimeout(2000);
conn.connect();
4. if (conn.getResponseCode() == 200) {
5. InputStream is = conn.getInputStream();
6. ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer))!=-1) {
out.write(buffer, 0, length);
}
String message = out.toString();
②POST方式
post方式跟get方式还是存在几个地方的差别的:
1.url的写法不一样,上面已经讲到,Get方式的URL地址需要在后面拼接传递的参数 如:?username=aaa&pwd=aaaa
Post方式不需要拼接,只需要接口的地址就可以。
2.Post方式与Get方式相比,多了2个请求头的配置跟1个请求数据
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", 数据.length()+"");
conn.setDoOutput(true);//设置该请求允许输出
conn.getOutputStream().write(数据.getBytes[], 0,数据.length());
或者:
OutputStream os = conn.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(object);
oos.flush();
oos.close();
os.close();
完整代码如下:
URL url= new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(2000);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length()+"");
// conn.getOutputStream().write(data.getBytes(), 0, data.length());
OutputStream os = conn.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(data);
oos.flush();
oos.close();
os.close();
if (conn.getResponseCode() == 200) {//说明此时请求成功
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!=-1){
bos.write(buffer, 0, len);
}
//对输出流进行操作
}
}catch(Exception e){
e.printStackTrace();
}