如何使用http将Android中的文件从移动设备发送到服务器?在Android中,如何使用http将文件(数据)从移动设备发送到服务器。
3 回答
GCT1015
TA贡献1827条经验 获得超4个赞
String url = "http://yourserver";File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
"yourfile");try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...} catch (Exception e) {
// show error}
富国沪深
TA贡献1790条经验 获得超9个赞
HttpClient http = AndroidHttpClient.newInstance("MyApp");HttpPost method = new HttpPost("
method.setEntity(new FileEntity(new File("path-to-file"), "application/octet-stream"));HttpResponse response = http.execute(method);
眼眸繁星
TA贡献1873条经验 获得超9个赞
public class AsyncHttpPostTask extends AsyncTask<File, Void, String> {
private static final String TAG = AsyncHttpPostTask.class.getSimpleName();
private String server;
public AsyncHttpPostTask(final String server) {
this.server = server;
}
@Override
protected String doInBackground(File... params) {
Log.d(TAG, "doInBackground");
HttpClient http = AndroidHttpClient.newInstance("MyApp");
HttpPost method = new HttpPost(this.server);
method.setEntity(new FileEntity(params[0], "text/plain"));
try {
HttpResponse response = http.execute(method);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
final StringBuilder out = new StringBuilder();
String line;
try {
while ((line = rd.readLine()) != null) {
out.append(line);
}
} catch (Exception e) {}
// wr.close();
try {
rd.close();
} catch (IOException e) {
e.printStackTrace();
}
// final String serverResponse = slurp(is);
Log.d(TAG, "serverResponse: " + out.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}}- 3 回答
- 0 关注
- 637 浏览
添加回答
举报
0/150
提交
取消
