package zzp.t.uploadfile;
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ProgressDialog dlg = new ProgressDialog(this);
dlg.setMessage("上传中...");
dlg.show();
new AsyncTask<Void, Void, HttpResponse>() {
@Override
protected HttpResponse doInBackground(Void... params) {
try {
HttpPost post = new HttpPost(
"http://veikr.com/myupload/upload.php");
File file = new File("/mnt/sdcard/infor.txt");
MultipartEntity multipart = new MultipartEntity();
multipart.addPart("name", new StringBody("veikr.com"));
multipart.addPart("file", new FileBody(file));
HttpClient client = new DefaultHttpClient();
post.setEntity(multipart);
HttpResponse response = client.execute(post);
return response;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(HttpResponse result) {
dlg.dismiss();
if (result != null) {
try {
new AlertDialog.Builder(MainActivity.this)
.setMessage(
EntityUtils.toString(result.getEntity()))
.create().show();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, "异常啊异常。。。", 0).show();
}
}
}.execute();
}
}
评论6
最新资源