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

简单的获取网络数据 测试使用

2017-01-04 16:38 555 查看
直接上代码

public void getHttpData(String strURL) {
HttpURLConnection connection = null;
try {
URL url = new URL(strURL);
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法,默认是GET
connection.setRequestMethod("GET");
// 设置字符集
connection.setRequestProperty("Charset", "UTF-8");
// 设置文件类型
connection.setRequestProperty("Content-Type",
"text/xml; charset=UTF-8");
// 设置请求参数,可通过Servlet的getHeader()获取
connection.setRequestProperty("Cookie",
"AppName=" + URLEncoder.encode("你好", "UTF-8"));
// 设置自定义参数
connection.setRequestProperty("MyProperty", "this is me!");

if (connection.getResponseCode() == 200) {
InputStream is = connection.getInputStream();
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
String strMyResult = byteArrayOutputStream.toString();
Log.i("after","测试数据"+strMyResult);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}

}


new  Thread(new Runnable() {
@Override
public void run() {
getHttpData("http://www.cnblogs.com/bokeyuan007/p/5550883.html");
}
}).start();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 网络
相关文章推荐