hupengwei 发表于 2013-1-14 18:00:07

Android 发送http请求

http请求其实是再普通不过的东西,网上也大把资料,但是鉴于在需要数据更新的安卓客户端里经常用到,在这里就把代码贴出来,已封装成一个方法,直接调用就好,方便各位。
这里我是直接通过get方式提交的:
private static final String ENCODE = "utf-8";public static final int TIMEOUT = 30000;// 30秒/** * 通过get方式提交参数给服务器 */private String sendGetRequest(String urlPath, Map<String, String> params)throws Exception {//根据传进来的链接和参数构建完整的urlStringBuilder sb = new StringBuilder(urlPath);if (params != null) {sb.append('?');for (Map.Entry<String, String> entry : params.entrySet()) {sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), ENCODE)).append('&');}}// 删掉多余的&sb.deleteCharAt(sb.length() - 1);Log.d("URL:", sb.toString());//打开链接,发送请求URL url = new URL(sb.toString());HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setRequestProperty("Content-Type", "text/xml");conn.setRequestProperty("Charset", ENCODE);conn.setConnectTimeout(TIMEOUT);Log.v("REQUEST", "服务器响应码:" + conn.getResponseCode());// 如果请求响应码是200,则表示成功if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {// 获得服务器返回的数据BufferedReader ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), ENCODE));String retData = null;String responseData = "";while ((retData = ins.readLine()) != null) {responseData += retData;}ins.close();return responseData;}return "sendGetRequest error!";} 调用:
String url = "http://1.hupengwei.sinaapp.com/index.php";// 向服务器端提交参数Map<String, String> map = new HashMap<String, String>();map.put("参数名1", 参数值1);map.put("参数名2", 参数值2);try {sendGetRequest(url,map);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} 
最后,别忘了在AnroidManifest.xml里加权限,这种2B错误不值得犯。
<uses-permission android:name="android.permission.INTERNET" /> 
页: [1]
查看完整版本: Android 发送http请求