这边只考虑json格式轻量级的数据请求。
除了部分像Build.VERSION.SDK_INT这样的只属于android的sdk API,其他是java通用。
URL openConnection获取的URLConnection实例由平台和http类型决定,比如安卓从4.4版本开始,http的url底层为com.android.okhttp.internal.http.HttpURLConnectionImpl,如果url是https的那么对应的是HttpsURLConnectionImpl。
对于Http(s)URLConnection,如果服务器返回的是正常的结果,那么对应的数据可以通过getInputStream获取;但是如果服务器返回的不是正常的结果,例如400,那么需要通过getErrorStream获取详细错误信息。以下的处理是直接通过捕捉IOException处理的,也可以通过getResponseCode先判断服务器状态,比如
HttpURLConnection httpConn = (HttpURLConnection)connection;
InputStream is;
if (httpConn.getResponseCode() >= 400) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
完整的请求
/**
* http get 请求
* @param url 请求uri
* @return HttpResponse请求结果实例
*/
public static Response httpGet(String url) {
Response response = null;
HttpURLConnection httpURLConnection = null;
try {
URL urlObj = new URL(url);
httpURLConnection = (HttpURLConnection) urlObj.openConnection();
httpURLConnection.setConnectTimeout(XZCache.getInstance().connectTimeout);
httpURLConnection.setReadTimeout(XZCache.getInstance().readTimeout);
httpURLConnection.setDoInput(true);
// 4.0 ~ 4.3 存在EOFException
if (Build.VERSION.SDK_INT > 13 && Build.VERSION.SDK_INT < 19) {
httpURLConnection.setRequestProperty("Connection", "close");
}
response = readStream(httpURLConnection);
} catch (MalformedURLException e) {
e.printStackTrace();
response = new Response();
response.content = e.getMessage();
response.code = -1;
} catch (IOException e) {
e.printStackTrace();
response = new Response();
response.content = e.getMessage();
response.code = -1;
} catch (Exception ex) {
ex.printStackTrace();
response = new Response();
response.content = ex.getMessage();
response.code = -1;
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
return response;
}
static Response readStream(HttpURLConnection connection) {
Response response = new Response();
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"));
int tmp;
while ((tmp = reader.read()) != -1) {
stringBuilder.append((char)tmp);
}
response.code = connection.getResponseCode();
response.content = stringBuilder.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
response.code = -1;
response.content = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
try {
//it could be caused by 400 and so on
reader = new BufferedReader(new InputStreamReader(
connection.getErrorStream(), "UTF-8"));
//clear
stringBuilder.setLength(0);
int tmp;
while ((tmp = reader.read()) != -1) {
stringBuilder.append((char)tmp);
}
response.code = connection.getResponseCode();
response.content = stringBuilder.toString();
} catch (IOException e1) {
response.content = e1.getMessage();
response.code = -1;
e1.printStackTrace();
} catch (Exception ex) {
//if user directly shuts down network when trying to write to server
//there could be NullPointerException or SSLException
response.content = ex.getMessage();
response.code = -1;
ex.printStackTrace();
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
//return null means successfully write to server
static Response writeStream(HttpURLConnection connection, String content) {
BufferedOutputStream out=null;
Response response = null;
try {
out = new BufferedOutputStream(connection.getOutputStream());
out.write(content.getBytes("UTF-8"));
out.flush();
} catch (IOException e) {
e.printStackTrace();
try {
//it could be caused by 400 and so on
response = new Response();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getErrorStream(), "UTF-8"));
StringBuilder stringBuilder = new StringBuilder();
int tmp;
while ((tmp = reader.read()) != -1) {
stringBuilder.append((char)tmp);
}
response.code = connection.getResponseCode();
response.content = stringBuilder.toString();
} catch (IOException e1) {
response = new Response();
response.content = e1.getMessage();
response.code = -1;
e1.printStackTrace();
} catch (Exception ex) {
//if user directly shutdowns network when trying to write to server
//there could be NullPointerException or SSLException
response = new Response();
response.content = ex.getMessage();
response.code = -1;
ex.printStackTrace();
}
} finally {
try {
if (out!=null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
/**
* http post 请求
* @param url 请求url
* @param jsonStr post参数
* @return HttpResponse请求结果实例
*/
public static Response httpPost(String url, String jsonStr) {
Response response = null;
HttpURLConnection httpURLConnection = null;
try {
URL urlObj = new URL(url);
httpURLConnection = (HttpURLConnection) urlObj.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(XZCache.getInstance().connectTimeout);
httpURLConnection.setReadTimeout(XZCache.getInstance().readTimeout);
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
httpURLConnection.setDoOutput(true);
httpURLConnection.setChunkedStreamingMode(0);
// 4.0 ~ 4.3 存在EOFException
if (Build.VERSION.SDK_INT > 13 && Build.VERSION.SDK_INT < 19) {
httpURLConnection.setRequestProperty("Connection", "close");
}
//start to post
response = writeStream(httpURLConnection, jsonStr);
if (response == null) { //if post successfully
response = readStream(httpURLConnection);
}
} catch (MalformedURLException e) {
e.printStackTrace();
response = new Response();
response.content = e.getMessage();
response.code = -1;
} catch (IOException e) {
e.printStackTrace();
response = new Response();
response.content = e.getMessage();
response.code = -1;
} catch (Exception ex) {
ex.printStackTrace();
response = new Response();
response.content = ex.getMessage();
response.code = -1;
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
return response;
}
public static class Response {
public Integer code;
public String content;
}