Android基于基于Http协议实现文件上传功能的方法协议实现文件上传功能的方法
本文实例讲述了Android基于Http协议实现文件上传功能的方法。分享给大家供大家参考,具体如下:
注意一般使用Http协议上传的文件都比较小,一般是小于2M
这里示例是上传一个小的MP3文件
1.主主Activity::MainActivity.java
public class MainActivity extends Activity
{
private static final String TAG = "MainActivity";
private EditText timelengthText;
private EditText titleText;
private EditText videoText;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//提交上传按钮
Button button = (Button) this.findViewById(R.id.button);
timelengthText = (EditText) this.findViewById(R.id.timelength);
videoText = (EditText) this.findViewById(R.id.video);
titleText = (EditText) this.findViewById(R.id.title);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String title = titleText.getText().toString();
String timelength = timelengthText.getText().toString();
Map<String, String> params = new HashMap<String, String>();
params.put("method", "save");
params.put("title", title);
params.put("timelength", timelength);
try
{
//得到SDCard的目录
File uploadFile = new File(Environment.getExternalStorageDirectory(), videoText.getText().toString());
//上传音频文件
FormFile formfile = new FormFile("02.mp3", uploadFile, "video", "audio/mpeg");
SocketHttpRequester.post("http://192.168.1.100:8080/videoweb/video/manage.do", params, formfile);
Toast.makeText(MainActivity.this, R.string.success, 1).show();
}
catch (Exception e)
{
Toast.makeText(MainActivity.this, R.string.error, 1).show();
Log.e(TAG, e.toString());
}
}
});
}
}
2.上传工具类上传工具类,注意里面构造协议字符串需要根据不同的提交表单来处理
public class SocketHttpRequester
{
/**
* 发送xml数据
* @param path 请求地址
* @param xml xml数据
* @param encoding 编码
* @return
* @throws Exception
*/
public static byte[] postXml(String path, String xml, String encoding) throws Exception{
byte[] data = xml.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml; charset="+ encoding);
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
评论0