举例:从网络上下载图片
String urlpath="http://i2.sinaimg.cn/dy/dsgb/20083.jpg"; try { URL url=new URL(urlpath); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(6000); con.setRequestMethod("GET"); if(con.getResponseCode()==200){ byte[] imagebytes = readStreamtoBytes(con.getInputStream()); File file =new File("pic.jpg"); FileOutputStream fos =new FileOutputStream(file); fos.write(imagebytes); fos.close(); }
public static byte[] readStreamtoBytes(InputStream instream) throws IOException{ ByteArrayOutputStream outstream =new ByteArrayOutputStream(); int len=-1; byte[] b = new byte[1024]; while((len = instream.read(b)) != -1){ outstream.write(b, 0, len); } outstream.flush(); outstream.close(); instream.close(); return outstream.toByteArray(); }
访问天气API
/* * 通过传递城市名称获得天气信息 * http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/ * getWeather?theCityCode=55&theUserID= */ public static String getWeatherMsgByCity(String cityName) { String url = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather"; HttpPost request = new HttpPost(url); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("theCityCode", cityName)); params.add(new BasicNameValuePair("theUserID", "")); String result = null; try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); request.setEntity(entity); HttpResponse response = new DefaultHttpClient().execute(request); if (response.getStatusLine().getStatusCode() == 200) { result = EntityUtils.toString(response.getEntity()); return parse2(result); } } catch (Exception e) { e.printStackTrace(); } return null; }
/* * 使用ksoap,获得城市列表 */ public static List<String> getCityList() { // 命名空间 String serviceNamespace = "http://WebXml.com.cn/"; // 请求URL String serviceURL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx"; // 调用的方法 String methodName = "getRegionProvince"; // 实例化SoapObject对象 SoapObject request = new SoapObject(serviceNamespace, methodName); // 获得序列化的Envelope SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = request; // envelope.encodingStyle = "UTF-8"; (new MarshalBase64()).register(envelope); // Android传输对象 AndroidHttpTransport ht = new AndroidHttpTransport(serviceURL); ht.debug = true; try { // 调用 ht.call("http://WebXml.com.cn/getRegionProvince", envelope); if (envelope.getResponse() != null) { return parse(envelope.bodyIn.toString()); } } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return null; }