1、get 请求
/** * get方式请求服务器 * * @param param 请求时包含的参数 * @return */ public static String get(RequestParam param) throws IOException, ServerException { String urlString = param.getUrl(); if (TextUtils.isEmpty(urlString)) return null; HttpURLConnection httpURLConnection = null; BufferedReader bufferedReader = null; try { URL url = new URL(urlString); // 打开连接 httpURLConnection = (HttpURLConnection) url.openConnection(); //设置读取超时 //设置连接超时 httpURLConnection.setReadTimeout(10 * 1000); httpURLConnection.setConnectTimeout(5 * 1000); // Set the post method. Default is GET httpURLConnection.setRequestMethod("GET"); httpURLConnection.connect(); if (httpURLConnection.getResponseCode() == 200) { bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8")); StringBuffer stringBuffer = new StringBuffer(); String lineStr = ""; while ((lineStr = bufferedReader.readLine()) != null) { stringBuffer.append(lineStr + "\n"); } return stringBuffer.toString(); } else { Log.w("HTTP", "请求服务器异常 " + httpURLConnection.getResponseCode()); throw new ServerException("服务器异常:" + httpURLConnection.getResponseCode()); } } finally { if(bufferedReader != null) bufferedReader.close(); if(httpURLConnection != null) httpURLConnection.disconnect(); } }
2、post 请求
/** * post 方式请求服务器 * * @param param 请求参数 * @return 响应 json 串 * @throws IOException 文本异常,超时等 */ public static String post(RequestParam param) throws IOException, ServerException { String urlString = param.getUrl(); if (TextUtils.isEmpty(urlString)) return null; HttpURLConnection httpURLConnection = null; OutputStreamWriter outputStreamWriter = null; BufferedReader bufferedReader = null; try { //url URL url = new URL(urlString); // 打开连接 httpURLConnection = (HttpURLConnection) url.openConnection(); //设置读取超时 //设置连接超时 httpURLConnection.setReadTimeout(10 * 1000); httpURLConnection.setConnectTimeout(5 * 1000); // Read from the connection. Default is true. httpURLConnection.setDoInput(true); // Output to the connection. Default is // false, set to true because post // method must write something to the // connection // 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true httpURLConnection.setDoOutput(true); // Post cannot use caches // Post 请求不能使用缓存 httpURLConnection.setUseCaches(false); // Set the post method. Default is GET httpURLConnection.setRequestMethod("POST"); // This method takes effects to // every instances of this class. // URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。 // connection.setFollowRedirects(true); // This methods only // takes effacts to this // instance. // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数 httpURLConnection.setInstanceFollowRedirects(true); // Set the content type to urlencoded, // because we will write // some URL-encoded content to the // connection. Settings above must be set before connect! // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode // 进行编码 httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, // 要注意的是connection.getOutputStream会隐含的进行connect。 httpURLConnection.connect(); // DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); // dataOutputStream.writeBytes(param.getParams()); // dataOutputStream.flush(); // dataOutputStream.close(); // flush and close// outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"); outputStreamWriter.write(param.getParams()); outputStreamWriter.flush(); if (httpURLConnection.getResponseCode() == 200) { bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8")); StringBuffer stringBuffer = new StringBuffer(); String lineStr = ""; while ((lineStr = bufferedReader.readLine()) != null) { stringBuffer.append(lineStr + "\n"); } return stringBuffer.toString(); } else { Log.w("HTTP", "请求服务器异常 " + httpURLConnection.getResponseCode()); throw new ServerException("服务器异常:" + httpURLConnection.getResponseCode()); } } finally { if(bufferedReader != null) bufferedReader.close(); if(outputStreamWriter != null) outputStreamWriter.close(); if(httpURLConnection != null) httpURLConnection.disconnect(); } }
RequestParam
/** * 描述:网络 请求参数 * @author HJK */ public class RequestParam { private String url; private Map<String, Object> params; public void put(String key, String value) { if (params == null) params = new HashMap<String, Object>(); params.put(key, value); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public List<NameValuePair> postParams() { if (params == null) return null; List<NameValuePair> param = new ArrayList<NameValuePair>(); for (String key:params.keySet()) param.add(new BasicNameValuePair(key, params.get(key)+"")); return param; } public String getParams() { if (params == null) return null; StringBuffer stringBuffer = new StringBuffer(); for (String key : params.keySet()) { stringBuffer.append(key).append("=").append(params.get(key)).append("&"); } if(stringBuffer.length()>0) stringBuffer.deleteCharAt(stringBuffer.length()-1); return stringBuffer.toString(); } public String toString() { return params == null?null:params.toString(); } }
ServerException
/** * 描述:服务器异常 * @author HJK */ public class ServerException extends Exception { public ServerException() { super(); } public ServerException(String msg) { super(msg); } public ServerException(String msg, Throwable cause) { super(msg, cause); } public ServerException(Throwable cause) { super(cause); } }