android 获取web 内容简单实现
16lz
2021-01-24
一种是HttpURLConnection 方法:
public String connect() throws IOException{URL url;url = new URL("http://192.168.1.109/SmartySpace/ZJClub/query.php?format=json");// 每个HttpURLConnection实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络HttpURLConnection conn = (HttpURLConnection) url.openConnection();//设置URL请求的方法 conn.setRequestMethod("GET"); //设置一个指定的超时值(以毫秒为单位),该值将在打开到此 URLConnection 引用的资源的通信链接时使用。conn.setConnectTimeout(5 * 1000); //conn.getInputStream()返回从此打开的连接读取的输入流 InputStream in=conn.getInputStream();System.out.println(in.available());ByteArrayOutputStream bout=new ByteArrayOutputStream();int c;while((c=in.read())!=-1){bout.write(c);}byte b[]=bout.toByteArray();in.close();bout.close();return new String(b);}另一种是apache的HttpClient包中的方法:
HttpClient client=new DefaultHttpClient();//POST urlString posturl="http://192.168.1.109/SmartySpace/ZJClub/query.php?format=json";//建立HttpPost对象HttpPost httpPost=new HttpPost(posturl);//建立一个NameValuePair数组,用于存储欲传递的参数List<BasicNameValuePair> params=new ArrayList<BasicNameValuePair>();//添加参数params.add(new BasicNameValuePair("user", "1"));//设置编码try {httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}//发送Post,并返回一个HttpResponse对象 HttpResponse response = null;try {response = client.execute(httpPost);} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}
更多相关文章
- Android通过url获取bitmap图片问题
- android通过NFC读取卡号
- Android(安卓)CardView+RecyclerView实现卡片列表
- android去除标题栏-------全屏运行AND 无标题栏 总结
- android:文件下载
- Android(安卓)源码解析 - ScrollView
- 系统命令行运行 android app程序
- Android(安卓): 自己写个HTTP框架
- android遇到的BUG