java - 如何在后台线程中使用 HttpPost 执行 MultipartEntity?

标签 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) {
            }

最佳答案

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

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

关于java - 如何在后台线程中使用 HttpPost 执行 MultipartEntity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13484342/

相关文章:

Android 未知主机异常

android - 使用 DataWedge 的广播 Intent 传递在 Android 应用程序中不起作用?

android - 在 Eclipse 的 Android Framework 类中是否有覆盖方法的快捷方式?

java - java中运行时连接和编译时连接的区别

java - 如何读取数字并将数字放入对象数组中

Android/iOS OpenCV 扩眼检测

android - 如何仅在侧面设置 View 阴影以进行高程 View

java - 在Java中,如何添加跨域访问

java - java中如何启动ThreadGroup?

java - 检查平衡括号 - nullPointerException