---
title: "【转】android httpclient 上传文件"
author: "foohsinglong"
date: "2012-04-10T15:33:20Z"
tags: []
categories: ["Web前端"]
slug: "android-httpclient"
draft: false
lastmod: "2012-04-10T15:33:20Z"
id: 1481823
url: "https://foohsinglong.iteye.com/blog/1481823"
---

```java
public void uploadFileClient()
  {
    Toast.makeText(this, "现在已经开始上传了！", Toast.LENGTH_LONG).show();
    String targetURL = actionUrl;// 上传指定URL

    File targetFile = new File(uploadFile);// 指定上传文件

    PostMethod filePost = new PostMethod(targetURL);

    try
    {

      // 通过以下方法可以模拟页面参数提交
      // filePost.setParameter("name", "中文");
      // filePost.setParameter("pass", "1234");
      byte[] buffer = new byte[1024];
      Part[] parts =
      { new FilePart(targetFile.getName() + System.currentTimeMillis(),
          targetFile) };

      filePost.setRequestEntity(new MultipartRequestEntity(parts,
          filePost.getParams()));
      HttpClient client = new HttpClient();
      client.getHttpConnectionManager().getParams()
          .setConnectionTimeout(5000);
      int status = client.executeMethod(filePost);

      if (status == HttpStatus.SC_OK)
      {
        System.out.println("上传成功");
        // 上传成功
      } else
      {
        System.out.println("上传失败");
        // 上传失败
      }
    } catch (Exception ex)
    {
      ex.printStackTrace();
    } finally
    {
      filePost.releaseConnection();
    }

  }
```