package com.example.uptoserverdemo;
import java.io.File; import java.io.IOException;
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.*; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.FileEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils;
import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.event.OnClick;
import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.TextView;
public class MainActivity extends Activity { private TextView tv; public static final String UP_URL = "http://169.254.109.73:8080/upserver/UploadFileServlet"; // private String filePath = "/storage/sdcard0/1461656337024acedownload.mp4"; // String fileName = "1461656337024acedownload.mp4"; private String filePath = "/mnt/sdcard/ace.mp4"; String fileName = "ace.mp4"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); ViewUtils.inject(this); } @OnClick(R.id.tv) public void jump(View view){ //异步上传文件 new MyAsyncTask().execute(); } class MyAsyncTask extends AsyncTask<String, Integer, String>{
@Override protected String doInBackground(String... params) { String rs = ""; String httpUrl = UP_URL+"?fileName="+fileName; HttpPost request = new HttpPost(httpUrl); File file = new File(filePath); //上传文件的配置代码 FileEntity entity = new FileEntity(file,"binary/octet-stream"); entity.setContentEncoding("binary/octet-stream"); request.setEntity(entity); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response; try { response = httpClient.execute(request); //如果返回状态为200,获得返回的结果 if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ //图片上传成功 Log.i("TAG","上传成功"); HttpEntity rsEntity = response.getEntity(); rs = EntityUtils.toString(rsEntity, "utf-8"); Log.i("TAG",rs); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return rs; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); tv.setText(result); } }
@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; }
}