Android新版sdk废除了对Apache的HttpClient。以前写的发送Http请求的轮子不能用了。所以用java底层支持的HttpURLConnection类重新造了一个轮子。
虽然Google官方推荐使用的volley框架使用的时候简单的多,但是过高的封装,导致某些特定的情况下,反而不方便(比如在非UI线程中需要进行网络操作时)。
以下是我的轮子的代码
public static JSONObject sendHttpPost(String url,HashMap<String , String > params){
URL realUrl = null ;
InputStream in = null ;
HttpURLConnection conn = null ;
StringBuffer sb = new StringBuffer();
if (params != null ){
for (Map.Entry<String ,String >e :params.entrySet()){
sb.append(e.getKey());
sb.append("=" );
sb.append(e.getValue());
sb.append("&" );
}
sb=sb.deleteCharAt(sb.length() - 1 );
}
String stringParams = sb.toString();
try {
realUrl = new URL(url);
conn = (HttpURLConnection)realUrl.openConnection();
conn.setDoOutput(true );
conn.setRequestMethod("POST" );
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.print(stringParams);
pw.flush();
pw.close();
in = conn.getInputStream();
}catch (Exception e){
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(in ));
StringBuffer buffer = new StringBuffer();
String line = "" ;
try {
while ((line = br.readLine()) != null ) {
buffer.append(line);
}
}catch (Exception e){
e.printStackTrace();
}
String result = buffer.toString();
Log.i(URLUtils.LOGTAG,"result = " + result);
JSONObject josonResult = null ;
try {
josonResult = new JSONObject(result);
}catch (Exception e){
e.printStackTrace();
}
return josonResult;
}