android 中的url操作
16lz
2021-12-04
android 中的url操作步骤
1、获取HttpClient对象
2、获取HttpGet对象,通过HttpGet对象可以对请求设置参数
3、通过HttpClient对象的excute方法得到HttpResponse对象
4、把HttpResponse对象获取返回的值
摘自android的document
1、获取HttpClient对象
2、获取HttpGet对象,通过HttpGet对象可以对请求设置参数
3、通过HttpClient对象的excute方法得到HttpResponse对象
4、把HttpResponse对象获取返回的值
摘自android的document
/** * Pull the raw text content of the given URL. This call blocks until the * operation has completed, and is synchronized because it uses a shared * buffer {@link #sBuffer}. * * @param url The exact URL to request. * @return The raw content returned by the server. * @throws ApiException If any connection or server error occurs. */ protected static synchronized String getUrlContent(String url) throws ApiException { if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } // Create client and set our specific user-agent string HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); request.setHeader("User-Agent", sUserAgent); try { HttpResponse response = client.execute(request); // Check if server response is valid StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HTTP_STATUS_OK) { throw new ApiException("Invalid response from server: " + status.toString()); } // Pull content stream from response HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } // Return result from buffered stream return new String(content.toByteArray()); } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } }
更多相关文章
- Android中 ScrollView(ListView)中嵌套ListView时显示不全的简便解
- Android(安卓)设备+APP+号码信息
- Android设备硬件序列号(SN、串号)分析
- Android多媒体学习三:实现自己的Camera
- Android之Handler用法总结
- 【Android】如何让跑马灯跑起来-控件请求焦点
- Android根据文件路径使用File类获取文件相关信息
- android获取GPS位置信息
- android 中的几种目录