Android基礎(chǔ)網(wǎng)絡(luò)第二天
1 post方式提交數(shù)據(jù)亂碼的解決
一般在公司開發(fā)客戶端和服務(wù)端的編碼要保持一致赋元。
android端的默認(rèn)編碼是utf-8;
做url請(qǐng)求時(shí)需要對(duì)參數(shù)進(jìn)行URLEncode編碼.
URL url = new URL("http://192.168.13.83:8080/itheima74/servlet/LoginServlet?username="+URLEncoder.encode(username)+"&pwd="+URLEncoder.encode(password));
connection.setDoOutput(true);
connection.getOutputStream().write(parmes.getBytes());
2 get方式提交數(shù)據(jù)亂碼解決
URLEncode
3 httpclient方式提交數(shù)據(jù)到服務(wù)器
HttpClient:
get方式:
//使用HttpClient請(qǐng)求服務(wù)器將用戶密碼發(fā)送服務(wù)器驗(yàn)證
try{
String path = "http://192.168.13.83:8080/itheima74/servlet/LoginServlet?username="+URLEncoder.encode(username,"utf-8")+"&pwd="+URLEncoder.encode(password,"utf-8");
//1.創(chuàng)建一個(gè)httpClient對(duì)象
HttpClient httpclient = new DefaultHttpClient();
//2.設(shè)置請(qǐng)求的方式
HttpGet httpget = new HttpGet(path);
//3.執(zhí)行一個(gè)http請(qǐng)求
HttpResponse response = httpclient.execute(httpget);
//4.獲取請(qǐng)求的狀態(tài)碼竿拆,
StatusLine statusLine = response.getStatusLine();
int code = statusLine.getStatusCode();
//5.判斷狀態(tài)碼后獲取內(nèi)容
if(code == 200){
HttpEntity entity = response.getEntity();//獲取實(shí)體內(nèi)容凰锡,中封裝的有http請(qǐng)求返回的流信息
InputStream inputStream = entity.getContent();
//將流信息轉(zhuǎn)換成字符串
String result = StreamUtils.streamToString(inputStream);
Message msg = Message.obtain();
msg.what = 1;
msg.obj = result;
handler.sendMessage(msg);
}
}catch (Exception e) {
e.printStackTrace();
}
post方式:
//使用UrlConncetion請(qǐng)求服務(wù)器將用戶密碼發(fā)送服務(wù)器驗(yàn)證
try{
String path = "http://192.168.13.83:8080/itheima74/servlet/LoginServlet";
//1.創(chuàng)建一個(gè)httpclient對(duì)象
HttpClient httpclient = new DefaultHttpClient();
//2.創(chuàng)建一個(gè)請(qǐng)求方式
HttpPost httppost = new HttpPost(path);
//創(chuàng)建集合封裝數(shù)據(jù)
ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
BasicNameValuePair nameValuePair = new BasicNameValuePair("username",username);
arrayList.add(nameValuePair);
BasicNameValuePair nameValuePair1 = new BasicNameValuePair("pwd",password);
arrayList.add(nameValuePair1);
//創(chuàng)建一個(gè)Entity
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(arrayList, "utf-8");
//設(shè)置請(qǐng)求時(shí)的內(nèi)容
httppost.setEntity(entity);
//3.執(zhí)行一個(gè)請(qǐng)求,返回一個(gè)response對(duì)象
HttpResponse response = httpclient.execute(httppost);
//4.獲取狀態(tài)碼
int code = response.getStatusLine().getStatusCode();
//5.判斷并獲取內(nèi)容
if(code == 200){
HttpEntity entity1 = response.getEntity();//獲取實(shí)體內(nèi)容,中封裝的有http請(qǐng)求返回的流信息
InputStream inputStream = entity1.getContent();
//將流信息轉(zhuǎn)換成字符串
String result = StreamUtils.streamToString(inputStream);
Message msg = Message.obtain();
msg.what = 2;
msg.obj = result;
handler.sendMessage(msg);
}
}catch (Exception e) {
e.printStackTrace();
}
4開源項(xiàng)目get post 方式提交 (asyncHttpClient)
get方式:
public static void requestNetForGetLogin(final Context context,final Handler handler ,final String username, final String password) {
//使用HttpClient請(qǐng)求服務(wù)器將用戶密碼發(fā)送服務(wù)器驗(yàn)證
try{
String path = "http://192.168.13.83:8080/itheima74/servlet/LoginServlet?username="+URLEncoder.encode(username,"utf-8")+"&pwd="+URLEncoder.encode(password,"utf-8");
//創(chuàng)建一個(gè)AsyncHttpClient對(duì)象
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
asyncHttpClient.get(path, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//statusCode:狀態(tài)碼 headers:頭信息 responseBody:返回的內(nèi)容,返回的實(shí)體
//判斷狀態(tài)碼
if(statusCode == 200){
//獲取結(jié)果
try {
String result = new String(responseBody,"utf-8");
Toast.makeText(context, result, 0).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
System.out.println("...............onFailure");
}
});
}catch (Exception e) {
e.printStackTrace();
}
}
post方式:
String path = "http://192.168.13.83:8080/itheima74/servlet/LoginServlet";
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("username", username);
params.put("pwd", password);
//url: parmas:請(qǐng)求時(shí)攜帶的參數(shù)信息 responseHandler:是一個(gè)匿名內(nèi)部類接受成功過失敗
asyncHttpClient.post(path, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//statusCode:狀態(tài)碼 headers:頭信息 responseBody:返回的內(nèi)容玷过,返回的實(shí)體
//判斷狀態(tài)碼
if(statusCode == 200){
//獲取結(jié)果
try {
String result = new String(responseBody,"utf-8");
Toast.makeText(context, result, 0).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
5 文件上傳的操作
使用第三方utils做文件上傳人乓。
public void fileupload(View v){
try{
EditText et_filepath = (EditText) findViewById(R.id.et_filepath);
//獲取輸入的文件地址
String filepath = et_filepath.getText().toString().trim();
//使用開源Utils做上傳操作
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("filename", new File(filepath));
//url : 請(qǐng)求服務(wù)器的url
asyncHttpClient.post("http://192.168.13.83:8080/itheima74/servlet/UploaderServlet", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if(statusCode == 200){
Toast.makeText(MainActivity.this, "上傳成功", 0).show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
}catch (Exception e) {
e.printStackTrace();
}
}
6 多線程加速下載的原理
1.線程越多下載越快?乳附? 不是内地。 與 本地網(wǎng)絡(luò)帶寬, 服務(wù)器資源的帶寬 有關(guān)
2.迅雷:3-5個(gè)赋除。
多線程下載的步驟:
1.要知道服務(wù)端資源的大小阱缓。
通過URLConnection請(qǐng)求服務(wù)器url獲取。
UrlConnection.getContentLength();//資源的大小
2.在本地創(chuàng)建一個(gè)與服務(wù)端資源同樣大小的一個(gè)文件(占位)
//file : 文件举农; mode:文件的模式荆针,rwd:直接寫到底層設(shè)備,硬盤
RandomAccessFile randomfile =new RandomAccessFile(File file,String mode)
randomfile.setLength(long size);//創(chuàng)建一個(gè)文件和服務(wù)器資源一樣大小
3.要分配每個(gè)線程下載文件的開始位置和結(jié)束位置颁糟。
4.開啟線程去執(zhí)行下載
通過UrlConnection下載部分資源航背。
注意:
1.需要Range頭,key:Range value:bytes:0-499
urlconnection.setRequestPropety("Range","bytes:0-499")
2.需要設(shè)置每個(gè)線程在本地文件的保存的開始位置
RandomAccessFile randomfile =new RandomAccessFile(File file,String mode)
randomfile.seek(int startPostion);//本次線程下載保存的開始位置棱貌。
5.要知道每個(gè)線程下載完畢玖媚。
7 javase 多線程下載
8 多線程斷點(diǎn)續(xù)傳實(shí)現(xiàn)
9 Android版本多線程下載
安智: sdcard沒有判斷。uc
10 開源項(xiàng)目實(shí)現(xiàn)多線程下載 (xutils)
public void download(View v){
EditText et_url = (EditText) findViewById(R.id.et_url);
String url = et_url.getText().toString().trim();
//1.創(chuàng)建httpUtils對(duì)象
HttpUtils httpUtils = new HttpUtils();
//2.調(diào)用download方法 url:下載的地址 target:下載的目錄 callback:回調(diào)
httpUtils.download(url, "/sdcard/feiqiu/feiq.exe", new RequestCallBack<File>() {
@Override
public void onLoading(long total, long current, boolean isUploading) {
System.out.println("total:"+total+";current:"+current);
super.onLoading(total, current, isUploading);
}
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
System.out.println(responseInfo.result);
}
@Override
public void onFailure(HttpException error, String msg) {
// TODO Auto-generated method stub
}
});
}