Android 万能Get请求Json方法
2012-10-30 14:54
375 查看
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 + "&"); } else { sBuffer.append(requestContent ); } } 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开发之开源框架OKHTTP的Get请求代码,得到json字符串方法
- android利用httpclient实现post、get请求restful接口进行json和form表单数据提交等公共方法类
- Android网络框架-Volley(四) 使用get和post方法发送json请求
- Android网络框架-Volley(四) 使用get和post方法发送json请求
- [置顶] Android开发之开源框架OKHTTP的Get请求代码,得到json字符串方法
- Android HTTP实例 使用GET方法和POST方法发送请求
- AJAX请求 $.getJson方法的使用
- 前端使用Jquery的getJSON方法,后台使用PHP,解决IE和火狐Firefox中存在的跨域ajax请求问题。
- Android HttpClient GET或者POST请求基本使用方法
- Android Get方法和POST方法发送请求
- 初涉Ajax,以post或get方法发送数据,以json或xml形式接收服务器返回的请求
- Android开发中使用Volley框架发送请求的get和post方法
- Android HTTP实例 使用GET方法和POST方法发送请求
- Android HttpClient GET或者POST请求基本使用方法
- Android使用Httpclient网络请求,get,post方法
- Android HttpClient GET或者POST请求基本使用方法
- Android中使用OkHttp包处理HTTP的get和post请求的方法
- Android HTTP实例 使用GET方法和POST方法发送请求
- JQurey中的getJSON方法请求的接口有错误时的处理方法
- HTTP协议下Android web应用GET和POST请求方法的请求、响应、传参