从Android应用(范例)上传文件和数据到服务器

・3 分钟阅读

你希望使用http请求将数据和文件发送到web服务器,典型的例子是在一个社交网络上编辑你的profile,发送一个文件数据(你的头像)。

以下片段应该在AsyncTask或类似内容中,它不能在UI线程内,因为如果您在主UI线程上执行http请求,最新的Android版本将直接地杀掉您的应用。

它需要导入以下:

 

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

下面是代码

 

HttpClient httpClient = new DefaultHttpClient();
StringBuilder builder = new StringBuilder();
try {
 HttpPost request = new HttpPost(TapabookUrls.urlSubirTapa);

 MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
 entity.addPart(" String_Data_Parameter_Name" , new StringBody(" String_Value" ));
 entity.addPart(" Numeric_Data_Parameter_Name" , new StringBody( NumericValue +" " ));

 /****************************/

 File f = new File(Environment.getExternalStorageDirectory()
 + File.separator +" test.jpg" );
 f.createNewFile();
 //write the bytes in file
 FileOutputStream fo = new FileOutputStream(f);
 fo.write(outStream.toByteArray());
 //remember close the FileOutput
 fo.close();
 FileBody picBody = new FileBody(f," image/jpeg" );

 /****************************/

 entity.addPart(" File_Parameter_Name" , picBody);
 request.setEntity(entity);
 HttpResponse response = httpClient.execute(request);
 StatusLine statusLine = response.getStatusLine();
 int statusCode = statusLine.getStatusCode();
 if (statusCode == 200) {
 HttpEntity responseEntity = response.getEntity();
 InputStream content = responseEntity.getContent(); 
 BufferedReader reader = new BufferedReader(new InputStreamReader(content));

 String line;
 while ((line = reader.readLine())!= null) {
 builder.append(line);
 }
 json = builder.toString();
 Tapabook.d(" SubeTapaAsincrono json :" + json);
 }

 } catch (IllegalStateException e) {
 Log.e(" FileUpload IllegalStateException" , e.getMessage() );
 } catch (IOException e) {
 Log.e(" FileUpload IOException" , e.getMessage() );
 } catch (ParseException e) {
 Log.e(" FileUpload ParseException" + e.getMessage() );

 } finally {
 //close connections
 httpClient.getConnectionManager().shutdown();
 }
Zas12357386 profile image