android常用代碼總結(二)

 

今天起了一個大早(相對于我以前),時不我待,沒有多少時間可以浪費了,繼續總結

先說說兩種方式的網絡操作,當然這些代碼我都是看過很多類似的代碼之后,覺得總結得非常之好的,拿來mark一下

.java.net包中的HttpUrlConnection

// Get方式請求

public static void requestByGet() throws Exception {

String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";

//新建一個URL對象

URL url = new URL(path);

//打開一個HttpURLConnection連接

HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

//設置連接超時時間

urlConn.setConnectTimeout(5 * 1000);

//開始連接

urlConn.connect();

//判斷請求是否成功

if (urlConn.getResponseCode() == HTTP_200) {

//獲取返回的數據

byte[] data = readStream(urlConn.getInputStream());

Log.i(TAG_GET, "Get方式請求成功,返回數據如下:");

Log.i(TAG_GET, new String(data, "UTF-8"));

} else {

Log.i(TAG_GET, "Get方式請求失敗");

}

//關閉連接

urlConn.disconnect();

}

Post方式

// Post方式請求

public static void requestByPost() throws Throwable {

String path = "https://reg.163.com/logins.jsp";

//請求的參數轉換為byte數組

String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")

+ "&pwd=" + URLEncoder.encode("android", "UTF-8");

byte[] postData = params.getBytes();

//新建一個URL對象

URL url = new URL(path);

//打開一個HttpURLConnection連接

HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

//設置連接超時時間

urlConn.setConnectTimeout(5 * 1000);

// Post請求必須設置允許輸出

urlConn.setDoOutput(true);

// Post請求不能使用緩存

urlConn.setUseCaches(false);

//設置為Post請求

urlConn.setRequestMethod("POST");

urlConn.setInstanceFollowRedirects(true);

//配置請求Content-Type

urlConn.setRequestProperty("Content-Type",

"application/x-www-form-urlencode");

//開始連接

urlConn.connect();

//發送請求參數

DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());

dos.write(postData);

dos.flush();

dos.close();

//判斷請求是否成功

if (urlConn.getResponseCode() == HTTP_200) {

//獲取返回的數據

byte[] data = readStream(urlConn.getInputStream());

Log.i(TAG_POST, "Post請求方式成功,返回數據如下:");

Log.i(TAG_POST, new String(data, "UTF-8"));

} else {

Log.i(TAG_POST, "Post方式請求失敗");

}

}

.org.apache.http包中的HttpGetHttpPost

get方式

// HttpGet方式請求

public static void requestByHttpGet() throws Exception {

String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";

//新建HttpGet對象

HttpGet httpGet = new HttpGet(path);

//獲取HttpClient對象

HttpClient httpClient = new DefaultHttpClient();

//獲取HttpResponse實例

HttpResponse httpResp = httpClient.execute(httpGet);

//判斷是夠請求成功

if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {

//獲取返回的數據

String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");

Log.i(TAG_HTTPGET, "HttpGet方式請求成功,返回數據如下:");

Log.i(TAG_HTTPGET, result);

} else {

Log.i(TAG_HTTPGET, "HttpGet方式請求失敗");

}

}

Post方式

// HttpPost方式請求

public static void requestByHttpPost() throws Exception {

String path = "https://reg.163.com/logins.jsp";

//新建HttpPost對象

HttpPost httpPost = new HttpPost(path);

// Post參數

List<NameValuePair> params = new ArrayList<NameValuePair>();

params.add(new BasicNameValuePair("id", "helloworld"));

params.add(new BasicNameValuePair("pwd", "android"));

//設置字符集

HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);

//設置參數實體

httpPost.setEntity(entity);

//獲取HttpClient對象

HttpClient httpClient = new DefaultHttpClient();

//獲取HttpResponse實例

HttpResponse httpResp = httpClient.execute(httpPost);

//判斷是夠請求成功

if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {

//獲取返回的數據

String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");

Log.i(TAG_HTTPGET, "HttpPost方式請求成功,返回數據如下:");

Log.i(TAG_HTTPGET, result);

} else {

Log.i(TAG_HTTPGET, "HttpPost方式請求失敗");

}

}

再談談文件操作,真的是毫無邏輯了,而且這些都是一些引子,引導我在今后的學習中不斷擴展.言歸正傳,文件分兩類,一類是手機內存,一類是SD Card,這兩種文件讀寫方式存在著差異,具體情況請看下面的代碼:

一. 手機內存

private String read() {

try {

FileInputStream fis = openFileInput(FILE);

byte[] buffer = new byte[1024];

int hasRead = 0;

StringBuilder sb = new StringBuilder("");

while ((hasRead = fis.read(buffer))> 0) {

sb.append(new String(buffer, 0, hasRead));

}

return sb.toString();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

private void write(String content)

{

try

{

// 以追加模式打開文件輸出流

FileOutputStream fos = openFileOutput(FILE, MODE_APPEND);

// FileOutputStream包裝成PrintStream

PrintStream ps = new PrintStream(fos);

// 輸出文件內容

ps.println(content);

ps.close();

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

二. SD card

private String read() {

// 如果手機插入了SD卡,而且應用程序具有訪問SD的權限

try {

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

// 獲取SD卡的目錄

File sdDirFile = Environment.getExternalStorageDirectory();

//獲取指定文件對應的輸入流

FileInputStream fis = new FileInputStream(sdDirFile.getCanonicalPath()+ FILE);

//將指定輸入流包裝成BufferedReader

BufferedReader br = new BufferedReader(new InputStreamReader(fis));

StringBuilder sb = new StringBuilder("");

String line = null;

while ((line =br.readLine())!=null) {

sb.append(line);

}

return sb.toString();

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

private void write(String context){

try {

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

File sdDir = Environment.getExternalStorageDirectory();

File targetFile = new File(sdDir.getCanonicalPath()+ FILE);

RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");

raf.seek(targetFile.length());

raf.write(context.getBytes());

raf.close();

}

} catch (Exception e) {

}

}

}

等我實際在操練一番,再繼續總結我所學到的東西吧,這里很多經驗都來自open 經驗庫,感謝那些分享的人

 本文由用戶 AndrLee 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!