android的自带的httpClient 怎么上传文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android的自带的httpClient 怎么上传文件相关的知识,希望对你有一定的参考价值。

这里只贴出代码,可根据实际情况自行修改。

[java]
package com.lxb.uploadwithprogress.http;

import java.io.File;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.lxb.uploadwithprogress.http.CustomMultipartEntity.ProgressListener;

public class HttpMultipartPost extends AsyncTask


private Context context;
private String filePath;
private ProgressDialog pd;
private long totalSize;

public HttpMultipartPost(Context context, String filePath)
this.context = context;
this.filePath = filePath;


@Override
protected void onPreExecute()
pd = new ProgressDialog(context);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage(Uploading Picture...);
pd.setCancelable(false);
pd.show();


@Override
protected String doInBackground(String... params)
String serverResponse = null;

HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(上传URL, 如:http://www.xx.com/upload.php);

try
CustomMultipartEntity multipartContent = new CustomMultipartEntity(
new ProgressListener()
@Override
public void transferred(long num)
publishProgress((int) ((num / (float) totalSize) * 100));

);

// We use FileBody to transfer an image
multipartContent.addPart(data, new FileBody(new File(
filePath)));
totalSize = multipartContent.getContentLength();

// Send it
httpPost.setEntity(multipartContent);
HttpResponse response = httpClient.execute(httpPost, httpContext);
serverResponse = EntityUtils.toString(response.getEntity());

catch (Exception e)
e.printStackTrace();


return serverResponse;


@Override
protected void onProgressUpdate(Integer... progress)
pd.setProgress((int) (progress[0]));


@Override
protected void onPostExecute(String result)
System.out.println(result: + result);
pd.dismiss();


@Override
protected void onCancelled()
System.out.println(cancle);



[java]
package com.lxb.uploadwithprogress.http;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;

public class CustomMultipartEntity extends MultipartEntity

private final ProgressListener listener;

public CustomMultipartEntity(final ProgressListener listener)
super();
this.listener = listener;


public CustomMultipartEntity(final HttpMultipartMode mode,
final ProgressListener listener)
super(mode);
this.listener = listener;


public CustomMultipartEntity(HttpMultipartMode mode, final String boundary,
final Charset charset, final ProgressListener listener)
super(mode, boundary, charset);
this.listener = listener;


@Override
public void writeTo(OutputStream outstream) throws IOException
super.writeTo(new CountingOutputStream(outstream, this.listener));


public static interface ProgressListener
void transferred(long num);


public static class CountingOutputStream extends FilterOutputStream

private final ProgressListener listener;
private long transferred;

public CountingOutputStream(final OutputStream out,
final ProgressListener listener)
super(out);
this.listener = listener;
this.transferred = 0;


public void write(byte[] b, int off, int len) throws IOException
out.write(b, off, len);
this.transferred += len;
this.listener.transferred(this.transferred);


public void write(int b) throws IOException
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);




上面为两个主要的类,下面放一个调用的Activity
参考技术A public String post(String pathToOurFile,String urlServer) throws ClientProtocolException, IOException, JSONException
HttpClient httpclient = new DefaultHttpClient();
//设置通信协议版本
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

//File path= Environment.getExternalStorageDirectory(); //取得SD卡的路径

//String pathToOurFile = path.getPath()+File.separator+"ak.txt"; //uploadfile
//String urlServer = "http://192.168.1.88/test/upload.php";

HttpPost httppost = new HttpPost(urlServer);
File file = new File(pathToOurFile);

MultipartEntity mpEntity = new MultipartEntity(); //文件传输
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("userfile", cbFile); // <input type="file" name="userfile" /> 对应的

httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());

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

System.out.println(response.getStatusLine());//通信Ok
String json="";
String path="";
if (resEntity != null)
//System.out.println(EntityUtils.toString(resEntity,"utf-8"));
json=EntityUtils.toString(resEntity,"utf-8");
JSONObject p=null;
try
p=new JSONObject(json);
path=(String) p.get("path");
catch(Exception e)
e.printStackTrace();


if (resEntity != null)
resEntity.consumeContent();


httpclient.getConnectionManager().shutdown();
return path;

以上是关于android的自带的httpClient 怎么上传文件的主要内容,如果未能解决你的问题,请参考以下文章

android的自带的httpClient 怎么上传文件

android和httpClient

httpclient4怎么使用请求超时后的重试?

httpclient (phpmyadmin) 无法在 Android 4.0+ 上运行

Android 6.0 使用 Apache HttpClient

Android studio 中想用 HttpClient 下载网络图片,却没有 HttpClient 以及相关的类