AsyncHttpClient POST上传文件

文件上传只能使用POST

package com.itheima.fileupload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

import org.apache.http.Header;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	private EditText et_path;

	private String uploadUrl = "http://192.168.12.31:8080/upload/UploadServlet";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//找到edittext
		et_path = (EditText) findViewById(R.id.et_path);
		
		
	}

	/**
	 * 文件上传的逻辑
	 * @param v
	 */
	public void upload(View v){
		// 拿到path 
		String path = et_path.getText().toString().trim();
		
		File file  = new File(path); 
		if (file!=null&&file.length()>0) {
			//文件上传 
			//1创建asynchttpclien 对象 
			AsyncHttpClient client = new AsyncHttpClient();
			//2设置参数,文件
			
			RequestParams params = new RequestParams();
			 params.put("username", "james");
			 params.put("password", "123456");
			 try {
				params.put("profile_picture", file);  // Upload a File
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} 

			//发送一个post请求
			client.post(uploadUrl, params, new AsyncHttpResponseHandler() {
				//请求成功的回调
				@Override
				public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
					Toast.makeText(getApplicationContext(), "成功", 1).show();
					
				}
				
				@Override
				public void onFailure(int statusCode, Header[] headers,
						byte[] responseBody, Throwable error) {
					
				}
			});
			
		}else {
			Toast.makeText(getApplicationContext(), "请选择上传的文件", 1).show();
		}
		
		
	}
	
}


你可能感兴趣的:(AsyncHttpClient,POST上传文件)