3

我正在实现一个与将文件发送到服务器相关的应用程序。

我正在尝试使用 http post 方法将文件发送到服务器。

我正在使用休闲代码从 sd 卡获取文件。

File root = Environment.getExternalStorageDirectory();
String pathToOurFile = root+"111";

我的代码看起来像休闲。

StringBuilder response = new StringBuilder();
try {
  HttpPost post = new HttpPost();
  post.setURI(uri);
  List params = new ArrayList();
  params.add(new BasicNameValuePair("paramName", "paramValue"));
  post.setEntity(new UrlEncodedFormEntity(params));
  DefaultHttpClient httpClient = new DefaultHttpClient();
  HttpResponse httpResponse = httpClient.execute(post);
  if (httpResponse.getStatusLine().getStatusCode() == 200) {
    Log.d(APP_TAG, "HTTP POST succeeded");
    HttpEntity messageEntity = httpResponse.getEntity();
    InputStream is = messageEntity.getContent();
    BufferedReader br = new BufferedReader(new InputStreamReader(
    openFileInput(pathToOurFile)));
    String line;

    while ((line = br.readLine()) != null) {
     Log.v("info",",,,"+line);
     response.append(line);
     }
   } else {
     Log.e(APP_TAG, "HTTP POST status code is not 200");
   }
} catch (Exception e) {
  Log.e(APP_TAG, e.getMessage());
}

但它不能正常工作。

如果知道解决方案请帮助我

提前致谢。

4

1 回答 1

3

这应该可以,但我还没有测试过代码。

 import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.DefaultHttpClient;

    ...

        public static void uploadFile() throws Exception {
            HttpClient httpclient = new DefaultHttpClient();
            try {
                HttpPost httppost = new HttpPost(uri);
                String pathToOurFile = root+"111";

                File f = new File(pathToOurFile);
                FileBody bin = new FileBody(f);


                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("file", bin);
                reqEntity.addPart("paramName", paramValue);

                httppost.setEntity(reqEntity);

                HttpResponse response = httpclient.execute(httppost);
                HttpEntity resEntity = response.getEntity();

                String postResponse = response.getStatusLine();
        }

    }
于 2012-11-09T05:53:53.137 回答