文件的上传

转载请注明出处:http://blog.csdn.net/u011569040/article/details/45165567

主要内容:

1.HTTP协议上传文件基本原理

2.使用HttpClient上传文件的方法

3.“乱码”问题的解决方法



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/uploadButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="upload" />

</RelativeLayout>
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	
	private Button button = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		 button = (Button) findViewById(R.id.uploadButton);
		 
		 button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				UploadThread ut = new UploadThread();
				ut.start();
			}
		});
	}

	//创建一个线程类,该类用于完成文件的上传操作
	class UploadThread extends Thread{

		@Override
		public void run() {
			super.run();
			//创建一个HttpClient对象
			HttpClient httpClient = new DefaultHttpClient();
			//创建HttpPost对象,上传文件只能使用Post方法,上传文件的URL由服务器开发人员规定
			HttpPost httpPost = new HttpPost("http://192.168.1.112:8080/UploadDemo/UploadServlet");
			//准备文件对象,首先得到SD卡路径
			String filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "dd.ppt";
			//生成文件对象
			File file = new File(filePath);
			//生成一个代表文件请求体内容的对象
			FileBody fileBody = new FileBody(file);
			
			//生成一个ContentType对象,该对象用于表示数据的类型,creat方法第一个参数用于指定数据的类型,第二个参数用于指定数据使用的字符集
			ContentType contentType = ContentType.create("text/html", "GBK");
			//生成一个代表字符串请求体内容的对象
			StringBody strBody = new StringBody("zhangsan",contentType); 
			
			//生成发往服务器的请求体对象
			//MultipartEntityBuilder对象用于设置MultipartEntity的相关内容
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			//向builder对象当中添加一个部分的请求体,第一个参数是发往服务器的键,第二个参数是发往服务器的值
			builder.addPart("uploadfile", fileBody);
			builder.addPart("testdata", strBody);
			//通过builder创建一个请求体对象
			HttpEntity entity = builder.build();
			httpPost.setEntity(entity);
			try {
				HttpResponse resp = httpClient.execute(httpPost);
				if(resp.getStatusLine().getStatusCode() == 200){
					HttpEntity en = resp.getEntity();
					//在读取服务器端的响应时,需要跟服务器端的开发人员确认字符编码
					BufferedReader reader = new BufferedReader(new InputStreamReader(en.getContent()));
					String result = reader.readLine();
					//此处打印的服务器端的响应是乱码,服务器端使用的是GBK编码
					//所以上面的代码应该写成:
			      //BufferedReader reader = new BufferedReader(new InputStreamReader(en.getContent(),"GBK"));
					Log.d("Upload", "result:" + result);
				}
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
}
加入网络和读写SD卡的权限:
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>




//生成一个代表文件请求体内容的对象
			FileBody fileBody = new FileBody(file);
FileBody需要导入httpcore-4.3.2.jar和httpmime-4.3.5.jar两个jar包,可以在 apache官网上下载,不会下载的话,我已打包上传了资源, csdn下载地址

而我是在这个网站上找到的http://repo1.maven.org/maven2/org/apache/httpcomponents/


怎么导入呢?把两个jar包复制到libs目录,在这个目录里选中,再Built Path





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值