您的位置:首页 > 理论基础 > 计算机网络

Android中的HttpURLConnection网络请求方式

2016-09-21 14:24 531 查看
转自:http://blog.csdn.net/ti2016/article/details/51873289


post请求

<span style="white-space:pre">	</span>String path="http://www.baidu.com";
String param="hehehe";

//新建一个URL对象
try {
URL url = new URL(path);
// 打开一个HttpURLConnection连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求方式请求post
conn.setRequestMethod("POST");
// Post请求必须设置允许输出
conn.setDoOutput(true);
// Post请求不能使用缓存
conn.setUseCaches(false);
// 配置请求Content-Type  Content-Length
conn.addRequestProperty("Content-Length", param.length()+"");
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
out.write(param.getBytes());
// 开始连接
conn.connect();
int code = conn.getResponseCode();
// 判断请求是否成功
if(code==200){
InputStream in= conn.getInputStream();
//把字节流转化成字符流  InputStreamReader
InputStreamReader isr=new InputStreamReader(in);
//把字符流转换成缓冲字符流
BufferedReader br=new BufferedReader(isr);
// 创建一个StringBuffer
StringBuffer sb=new StringBuffer();
String str="";
while((str=br.readLine())!=null){
sb.append(str);
}

}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


get请求

<span style="white-space:pre">	</span>//网址
String path="http://www.baidu.com";

try {
//新建一个URL对象
URL url = new URL(path);
// 打开一个HttpURLConnection连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求方式get请求
conn.setRequestMethod("GET");
// 设置连接超时时间
conn.setConnectTimeout(5000);
// //再设置超时时间
conn.setReadTimeout(5000);
// 开始连接
conn.connect();
// 判断请求是否成功     成功码为200
if(200==conn.getResponseCode()){
InputStream inputStream = conn.getInputStream();
//把字节流转化成字符流  InputStreamReader
InputStreamReader isr=new InputStreamReader(inputStream);
//把字符流转换成缓冲字符流
BufferedReader br=new BufferedReader(isr);
// 创建一个StringBuffer
StringBuffer sb=new StringBuffer();
String str="";
while((str=br.readLine())!=null){
sb.append(str);
}

}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐