Android 万能Get请求Json方法
2012-10-30 15:38:46 来源:WEB开发网核心提示:package com.example.h3c.net;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.ConnectException;import ja
package com.example.h3c.net; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.util.Log; import com.example.pickride.util.ConstantsTable; public class HttpConnection { private final int TIMEOUT = 3000;// 设定超时时间 /** * 请求服务器响应 * * @param requestType * 请求类型 requestContent [类型,参数,类型,参数] */ public String requestService(String requestType, String... requestContent) { String resultData = ""; InputStreamReader in = null; HttpURLConnection urlConn = null; BufferedReader buffer = null; try { StringBuffer sBuffer = new StringBuffer(); for (int n = 0; n < requestContent.length; n++) { if ((n + 1) % 2 == 0) { sBuffer.append("=" + requestContent[n] + "&"); } else { sBuffer.append(requestContent[n]); } } URL url = new URL(ConstantsTable.URI + requestType + "?" + sBuffer); if (url != null) { urlConn = (HttpURLConnection) url.openConnection(); urlConn.setConnectTimeout(TIMEOUT);// 设置超时时间 try { in = new InputStreamReader(urlConn.getInputStream()); } catch (ConnectException e) { Log.e(ConstantsTable.LOG_TAG, "服务器宕机了..."); return resultData; } buffer = new BufferedReader(in); String inputLine = null; while ((inputLine = buffer.readLine()) != null) { resultData += inputLine + "\n"; } urlConn.disconnect(); if (ConstantsTable.DEBUG_FLAG) { Log.d(ConstantsTable.LOG_TAG, resultData); } } } catch (MalformedURLException e) { Log.e(ConstantsTable.LOG_TAG, "域名无法解析"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (buffer != null) { buffer.close(); } } catch (IOException e) { e.printStackTrace(); } } return resultData; } }
- ››Android 当修改一些代码时,使用什么编译命令可以最...
- ››Android 如何添加一个apk使模拟器和真机都编译进去...
- ››Android 修改Camera拍照的默认保存路径
- ››Android 如何修改默认输入法
- ››android开发中finish()和System.exit(0)的区别
- ››Android手势识别简单封装类
- ››android中查看项目数字证书的两种方法
- ››Android中获取IMEI码的办法
- ››android 相机报错 setParameters failed
- ››Android重启运用程序的代码
- ››Android为ListView的Item设置不同的布局
- ››android bitmap与base64字符串的互相转换
更多精彩
赞助商链接