一、關於網絡請求方式,大家不外乎用HttpCLient,HttpURLConnection,以及第三方jar封裝的請求方式。但是近期Google在安卓6.0之後刪除了HttpClient,強制不讓使用了,那麼肯定有一直在使用HttpClient請求方式的程序員們,就像我,一直用HttpClient,忘記了HttpURLConnection請求方式,後來自己翻翻筆記,爲了以後不忘記,特意寫篇文章記一下。
代碼如下:
/*
* 訪問網絡的方法
*/
protected void query() {
String trim = ev_city.getText().toString().trim();
String str;
try {
str = URLEncoder.encode(trim,"utf-8");
String path="http://www.baidu.com";
//獲取網絡路徑
URL url = new URL(path);
//打開連接
HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
//設置連接超時時間
openConnection.setConnectTimeout(5000);
//設置讀取超時時間
openConnection.setReadTimeout(5000);
//設置請求方式
openConnection.setRequestMethod("GET");
//得到網絡返回的響應碼
int responseCode = openConnection.getResponseCode();
if (responseCode==200) {
//得到網絡輸入流
InputStream inputStream = openConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[1024];
while((len=inputStream.read(buffer))!=-1){
baos.write(buffer,0,len);
}
String string = baos.toString();
handler.obtainMessage(SUCCESS, string).sendToTarget();
}else{
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "請求網絡失敗!", 0).show();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
二、關於異步任務,就不多說了,大家用過之後都知道其好處。直接上代碼:
/*
* 自定義一個MyAsyncTask類
*/
class MyAsynctask extends AsyncTask<String, Void, MenuInfo> {
private ArrayList<Data> list;
@Override
protected Object doInBackground(String... params) {
//得到網絡上的數據
//在這裏調用請求網絡的方法
Object object= getDish(params[0]);
return object;
}
@Override
protected void onPostExecute(Object object) {
super.onPostExecute(object);
//得到解析內容
//這裏做設置數據的方法
}
});
}
}
/**
* 搜索按鈕
*/
public void search(View v) {
new Thread() {
public void run() {
try {
// 獲取MyAsynctask對象
MyAsynctask asynctask = new MyAsynctask();
// 得到輸入框的內容
String str = ev_dishName.getText().toString().trim();
//執行異步任務
asynctask.execute(str);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
以上就是HttpURLConnection和AsyncTask的用法了。