編輯:關於Android編程
/**
* HttpURLConnection post方式請求服務器
* @param urlpath
* @param requestData
* @return
* @throws IOException
*/
public static String requestByPost(String urlpath,String requestData) throws IOException{
// HTTP connection reuse which was buggy pre-froyo
//froyo之前的系統使用httpurlconnection存在bug
/*Workaround for bug pre-Froyo, see here for more info:
http://android-developers.blogspot.com/2011/09/androids-http-clients.html*/
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
URL url = new URL(urlpath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(TIMEOUT);
conn.setReadTimeout(TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
//需要設置 gzip的請求頭 才可以獲取Content-Encoding響應碼
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect();
String urlEncodedRequestStr = URLEncoder.encode(requestData,"utf-8");
String requestStr = "jsonStr="+urlEncodedRequestStr;
conn.getOutputStream().write(requestStr.getBytes("utf-8"));
conn.getOutputStream().flush();
conn.getOutputStream().close();
// //獲取所有響應頭字段
// Map< String,List< String>> map = conn.getHeaderFields();
// //遍歷所有的響應頭字段
// if(null!=map){
// for (String key : map.keySet()){
// System.out.println(key + "--->" + map.get(key));
// }
// }
String content_encode = conn.getContentEncoding();
System.out.println("content_encode:"+content_encode);
// int responseCode = conn.getResponseCode();
// System.out.println("responseCode:"+responseCode);
// if(responseCode != 200){
// String message = conn.getResponseMessage();
// throw new IOException("ResponseCode:"+responseCode+",Message:"+message);
// }
//如果是gzip的壓縮流 進行解壓縮處理
if(null!=content_encode&&!"".equals(content_encode)&&content_encode.equals("gzip")){
GZIPInputStream in = new GZIPInputStream(conn.getInputStream());
if(in == null){
return "";
}
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
int len ;
byte [] buffer = new byte[1024];
while((len=in.read(buffer))!= -1){
arrayOutputStream.write(buffer, 0, len);
}
in.close();
arrayOutputStream.close();
conn.disconnect();
str = new String(arrayOutputStream.toByteArray(),"utf-8");
//正常流處理
}else{
InputStream in = conn.getInputStream();
if(in == null){
return "";
}
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
int len ;
byte [] buffer = new byte[1024];
while((len=in.read(buffer))!= -1){
arrayOutputStream.write(buffer, 0, len);
}
in.close();
arrayOutputStream.close();
conn.disconnect();
str = new String(arrayOutputStream.toByteArray(),"utf-8");
}
return str;
}
添加的注釋是項目中實際遇到的問題,記下來小小總結下!
ContentProvider的一個重要的特點就是它是可以使得某些數據可以被跨進程訪問,一般我們的數據庫是不可跨進程被訪問,因為數據庫一般的數據是屬於某個應用程序的,如果
1 . 以下集合對象中哪幾個是線程安全的?(B,C,D )A: ArrayListB: VectorC: HashtableD: Stack解析:下面是這些線程安全的同步
1.場景還原之FliddlerFiddler是一款抓包神器,近日,由於項目中要嵌入H5頁面,公司又沒專門的UI設計師,所以你懂得,這個任務就要給我喽!可憐的我並沒有藝術細
android_apk的在線安裝,除了要設計Android 客戶端的代碼外,還要搭建服務器的代碼,仿真實現中Android軟件的在線升級。 Android 客