如何在后台线程中使用HttpPost进行MultipartEntity?

时间:2012-11-21 00:05:10

标签: java android

如何执行此代码以便在后台线程中发送?

// TODO: Send image in background
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(urlString);

            try {
              MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
              entity.addPart("userfile", new FileBody(f));
              httppost.setEntity(entity);
              HttpResponse response = httpclient.execute(httppost);
              BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
              String sResponse;
              StringBuilder s = new StringBuilder();

              while ((sResponse = reader.readLine()) != null) {
                  s = s.append(sResponse); 
              }
              Log.d("Response", "Response: " + s);
            } 
            catch (ClientProtocolException e) {
            } 
            catch (IOException e) {
            }

1 个答案:

答案 0 :(得分:1)

在后台线程中执行任何操作的方式相同 - 启动一个线程来执行此操作。在Android上,您可以使用AsyncTask在后​​台执行内容并在完成后更新UI。

http://developer.android.com/reference/android/os/AsyncTask.html