1 post方式提交数据乱码的解决
做url请求时需要对参数进行URLEncode编码.
URL url = new URL("http://192.168.13.83:8080/jwb/servlet/LoginServlet?username="+URLEncoder.encode(username)+"&pwd="+URLEncoder.encode(password));
connection.setDoOutput(true);
connection.getOutputStream().write(parmes.getBytes());
2 httpclient方式提交数据到服务器
HttpClient:
get方式:
try{
String path = "http://192.168.13.83:8080/jwb/servlet/LoginServlet?username="+URLEncoder.encode(username,"utf-8")+"&pwd="+URLEncoder.encode(password,"utf-8");
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(path);
HttpResponse response = httpclient.execute(httpget);
StatusLine statusLine = response.getStatusLine();
int code = statusLine.getStatusCode();
if(code == 200){
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
String result = StreamUtils.streamToString(inputStream);
Message msg = Message.obtain();
msg.what = 1;
msg.obj = result;
handler.sendMessage(msg);
}
}catch (Exception e) {
e.printStackTrace();
}
post方式:
try{
String path = "http://192.168.13.83:8080/jwb/servlet/LoginServlet";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(path);
ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
BasicNameValuePair nameValuePair = new BasicNameValuePair("username",username);
arrayList.add(nameValuePair);
BasicNameValuePair nameValuePair1 = new BasicNameValuePair("pwd",password);
arrayList.add(nameValuePair1);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(arrayList, "utf-8");
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
int code = response.getStatusLine().getStatusCode();
if(code == 200){
HttpEntity entity1 = response.getEntity();
InputStream inputStream = entity1.getContent();
String result = StreamUtils.streamToString(inputStream);
Message msg = Message.obtain();
msg.what = 2;
msg.obj = result;
handler.sendMessage(msg);
}
}catch (Exception e) {
e.printStackTrace();
}
3开源项目get post 方式提交 (asyncHttpClient)
get方式:
public static void requestNetForGetLogin(final Context context,final Handler handler ,final String username, final String password) {
try{
String path = "http://192.168.13.83:8080/jwb
/servlet/LoginServlet?username="+URLEncoder.encode(username,"utf-8")+"&pwd="+URLEncoder.encode(password,"utf-8");
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
asyncHttpClient.get(path, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if(statusCode == 200){
try {
String result = new String(responseBody,"utf-8");
Toast.makeText(context, result, 0).show();
} catch (UnsupportedEncodingException e) {
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/jwb/servlet/LoginServlet";
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("username", username);
params.put("pwd", password);
asyncHttpClient.post(path, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if(statusCode == 200){
try {
String result = new String(responseBody,"utf-8");
Toast.makeText(context, result, 0).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
4 文件上传的操作
使用第三方utils做文件上传。
public void fileupload(View v){
try{
EditText et_filepath = (EditText) findViewById(R.id.et_filepath);
String filepath = et_filepath.getText().toString().trim();
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("filename", new File(filepath));
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();
}
}
5 多线程加速下载的原理
线程越多下载越快?? 不是。 与 本地网络带宽, 服务器资源的带宽 有关
多线程下载的步骤:
1.要知道服务端资源的大小。
通过URLConnection请求服务器url获取。
UrlConnection.getContentLength();
2.在本地创建一个与服务端资源同样大小的一个文件(占位)
//file : 文件; mode:文件的模式,rwd:直接写到底层设备,硬盘
RandomAccessFile randomfile =new RandomAccessFile(File file,String mode)
randomfile.setLength(long size);
3.要分配每个线程下载文件的开始位置和结束位置。
4.开启线程去执行下载
通过UrlConnection下载部分资源。
注意:
1.需要Range头,key:Range value:bytes:0-499
urlconnection.setRequestPropety("Range","bytes:0-499")
2.需要设置每个线程在本地文件的保存的开始位置
RandomAccessFile randomfile =new RandomAccessFile(File file,String mode)
randomfile.seek(int startPostion)
5.要知道每个线程下载完毕。
6 开源项目实现多线程下载 (xutils)
public void download(View v){
EditText et_url = (EditText) findViewById(R.id.et_url);
String url = et_url.getText().toString().trim();
HttpUtils httpUtils = new HttpUtils();
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) {
}
});
}