最基本的使用代码:
(访问baidu首页)
HttpURLConnection urlConnection = null; try { URL url = new URL("http://www.baidu.com/"); urlConnection = (HttpURLConnection)url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); String result = readInStream(in); handleResult(result); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { urlConnection.disconnect(); }
private String readInStream(InputStream in) { Scanner scanner = new Scanner(in).useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : ""; }
<uses-permission android:name="android.permission.INTERNET"/>不然就会有UnKnownHostException.
默认的,不给urlConnection添加任何属性的话是使用Get方法,如果用Post可以:
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
当然还可以用setRequestProperty方法给请求添加:Host,Content-Type,Content-Lenth,Authentication等参数
再使用Post的时候还有一个注意点在官方文档中提及的:上传数据到服务器时为了达到最好的性能,你可以在知道数据固定大小长度的情况下使用 setFixedLengthStreamingMode(int) 方法,或者在不知道长度的情况下使用setChunkedStreamingMode(int)。因为如果不这样的话,HttpURLConnection 在发生请求之前是将数据全部放到内存里面的,这样浪费内存(会造成OutOfMemoryError)而且延时。这个东西再这里详细说了:http://www.mzone.cc/article/198.html
附带一个Post xml的例子:
HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) new URL(url).openConnection(); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setChunkedStreamingMode(0); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", ("application/xml; charset=utf-8").replaceAll("\\s", "")); urlConnection.setRequestProperty("Content-Length", String.valueOf(Xml.getBytes().length)); OutputStream out = urlConnection.getOutputStream(); out.write(Xml.getBytes()); out.close(); int responseCode = urlConnection.getResponseCode(); InputStream in = null; if (responseCode == 200) { in = new BufferedInputStream(urlConnection.getInputStream()); } else { in = new BufferedInputStream(urlConnection.getErrorStream()); } String result = readInStream(in); handleResult(result); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { urlConnection.disconnect(); }