这个是用第三方库做的文件上传。稳定性还不错。然后使用简单。我进一步简化了。更简单使用。
使用的包是httpmime-4.1.2.jar(http://download.csdn.net/detail/u012565107/7005475)。
加上我改写的HttpClientImp(主要部分是当年看师兄代码写的。顺便在此感谢一下大神师兄。跑题了。。。。)
先看看怎么使用HttpClientImp吧
//这是单例模式 所以不要去new 一个 HttpClientImp httpClientImp = HttpClientImp.INSTANCE; List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("data",189)); //根据自己需求 可以post,get等请求。 Session 填上null就行了。 //得到的jsonStr就是 http访问返回的字符串。然后把jsonStr哪去按自己需求处理 String jsonStr = httpClientImp.postForString("url_api", null, nameValuePairs);
HttpClientImp httpClientImp = HttpClientImp.INSTANCE; File file = new File("/sdcard/test.png"); if(file.exists() && file.isFile()){ Map<String, String> param = new HashMap<String, String>(); param.put("data","myContent"); Map<String, File> fileMap = new HashMap<String, File>(); fileMap.put("fileData", file); //非文件的参数 用Map<String, String>的键值对传进去 就是param //文件参数 也用Map<String, File>的键值对传递进去 fileMap。 String jsonStr= httpClientImp.postForString(URLConstant.REPLY_SEND, param, fileMap); }
import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.params.HttpClientParams; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.params.ConnPerRoute; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; 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; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import android.text.TextUtils; public class HttpClientImp { private static final String TAG = "HttpClient"; private static final int MAX_CONNECTIONS_PER_ROUTE = 8; private static final int MAX_CONNECTION = 16; public static final String COOKIE = "Cookie"; public static final String SESSIONID = "JSESSIONID="; public static final int TIMEOUT = 300000; private static final String DEFAULT_CLIENT_VERSION = "com.znisea.linju"; private static final String CLIENT_VERSION_HEADER = "User-Agent"; private final HttpClient mHttpClient; private final String mClientVersion; /** * singleton */ public static HttpClientImp INSTANCE = new HttpClientImp(); private HttpClientImp() { mHttpClient = createHttpClient(); mClientVersion = DEFAULT_CLIENT_VERSION; } /** * execute a HttpPost * * @param url * not null * @param sessionId * allow null * @param list * @return String */ public String postForString(String url, String sessionId, List<NameValuePair> list) throws Exception { HttpPost httpPost = createHttpPost(url, sessionId, list); HttpResponse response = executeHttpRequest(httpPost); switch (response.getStatusLine().getStatusCode()) { case 200: try { return EntityUtils.toString(response.getEntity()); } catch (ParseException e) { throw new Exception(e.getMessage()); } case 401: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); case 404: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); default: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); } } /** * execute a HttpPost * * @param url * not null * @param sessionId * allow null * @param * @return String */ public String postForString(String url, String sessionId, NameValuePair nameValuePair) throws Exception { List<NameValuePair> list = new ArrayList<NameValuePair>(); list.add(nameValuePair); return postForString(url, sessionId, list); } /** * execute a HttpPost * * @param url * not null * @param sessionId * allow null * @param * @return InputStream */ public InputStream postForStream(String url, String sessionId, List<NameValuePair> list) throws Exception { HttpPost httpPost = createHttpPost(url, sessionId, list); HttpResponse response = executeHttpRequest(httpPost); switch (response.getStatusLine().getStatusCode()) { case 200: try { return response.getEntity().getContent(); } catch (ParseException e) { throw new Exception(e.getMessage()); } case 401: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); case 404: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); default: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); } } /** * execute a HttpPost * * @param url * not null * @param sessionId * allow null * @param * @return InputStream */ public InputStream postForStream(String url, String sessionId, NameValuePair nameValuePair) throws Exception { List<NameValuePair> list = new ArrayList<NameValuePair>(); list.add(nameValuePair); return postForStream(url, sessionId, list); } public String postForString(String url,Map<String, String> params, Map<String, File> files) throws Exception{ HttpPost post = new HttpPost(url); post.addHeader(CLIENT_VERSION_HEADER, mClientVersion); MultipartEntity entity = new MultipartEntity(); for (Map.Entry<String, String> entry : params.entrySet()) { entity.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.forName("UTF-8"))); // System.out.println(entry.getKey() +" "+entry.getValue()); } if(files != null){ for (Map.Entry<String, File> file : files.entrySet()) { // entity.addPart(file.getKey(),new FileBody(file.getValue())); entity.addPart(file.getKey(),new FileBody(file.getValue())); // System.out.println(file.getKey()); } } post.setEntity(entity); HttpResponse response = mHttpClient.execute(post); return EntityUtils.toString(response.getEntity()); } /** * execute a HttpGet * * @param url * not null * @param sessionId * allow null * @return String * @throws Exception */ public String getForString(String url, String sessionId) throws Exception { HttpGet httpGet = createHttpGet(url, sessionId); HttpResponse response = executeHttpRequest(httpGet); switch (response.getStatusLine().getStatusCode()) { case 200: try { return EntityUtils.toString(response.getEntity()); } catch (ParseException e) { throw new Exception(e.getMessage()); } case 401: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); case 404: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); default: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); } } public String getForString(String url, String sessionId, NameValuePair nameValuePair) throws Exception { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(nameValuePair); return getForString(url, sessionId, nameValuePairs); } public String getForString(String url, String sessionId, List<NameValuePair> nameValuePairs) throws Exception { HttpGet httpGet = createHttpGet(url, sessionId, nameValuePairs); HttpResponse response = executeHttpRequest(httpGet); switch (response.getStatusLine().getStatusCode()) { case 200: try { return EntityUtils.toString(response.getEntity()); } catch (ParseException e) { throw new Exception(e.getMessage()); } case 401: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); case 404: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); default: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); } } /** * execute a HttpGet * * @param url * not null * @param sessionId * allow null * @return String * @throws Exception */ public InputStream getForStream(String url, String sessionId) throws Exception { HttpGet httpGet = createHttpGet(url, sessionId); HttpResponse response = executeHttpRequest(httpGet); switch (response.getStatusLine().getStatusCode()) { case 200: try { return response.getEntity().getContent(); } catch (ParseException e) { throw new Exception(e.getMessage()); } case 401: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); case 404: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); default: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); } } /** * execute a HttpGet * * @param url * @param nameValuePairs * @return * @throws Exception */ public InputStream getForStream(String url, String sessionId, List<NameValuePair> nameValuePairs) throws Exception { HttpGet httpGet = createHttpGet(url, sessionId, nameValuePairs); HttpResponse response = executeHttpRequest(httpGet); switch (response.getStatusLine().getStatusCode()) { case 200: try { return response.getEntity().getContent(); } catch (ParseException e) { throw new Exception(e.getMessage()); } case 401: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); case 404: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); default: response.getEntity().consumeContent(); throw new Exception(response.getStatusLine().toString()); } } /** * execute() an httpRequest catching exceptions and returning null instead. * * @param httpRequest * @return * @throws IOException */ public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) throws IOException { try { mHttpClient.getConnectionManager().closeExpiredConnections(); return mHttpClient.execute(httpRequest); } catch (IOException e) { httpRequest.abort(); throw e; } } /** * create HttpGet */ public HttpGet createHttpGet(String url, String sessionId) { HttpGet httpGet = new HttpGet(url); httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion); if (!TextUtils.isEmpty(sessionId)) { httpGet.addHeader(COOKIE, SESSIONID + sessionId); } return httpGet; } /** * create HttpGet */ public HttpGet createHttpGet(String url, String sessionId, List<NameValuePair> nameValuePairs) { String query = URLEncodedUtils.format(nameValuePairs, HTTP.UTF_8); HttpGet httpGet = new HttpGet(url + "?" + query); httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion); if (!TextUtils.isEmpty(sessionId)) { httpGet.addHeader(COOKIE, SESSIONID + sessionId); } return httpGet; } /** * create HttpPost */ public HttpPost createHttpPost(String url, String sessionId, List<NameValuePair> list) { HttpPost httpPost = new HttpPost(url); httpPost.addHeader(CLIENT_VERSION_HEADER, mClientVersion); if (!TextUtils.isEmpty(sessionId)) { httpPost.addHeader(COOKIE, SESSIONID + sessionId); } try { httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); } catch (UnsupportedEncodingException e1) { throw new IllegalArgumentException( "Unable to encode http parameters."); } return httpPost; } /** * Create a thread-safe client. This client does not do redirecting, to * allow us to capture correct "error" codes. * * @return HttpClient */ public final DefaultHttpClient createHttpClient() { // Sets up the http part of the service. final SchemeRegistry supportedSchemes = new SchemeRegistry(); // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. final SocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", sf, 80)); // Set some client http client parameter defaults. final HttpParams httpParams = createHttpParams(); HttpClientParams.setRedirecting(httpParams, false); final ClientConnectionManager ccm = new ThreadSafeClientConnManager( httpParams, supportedSchemes); return new DefaultHttpClient(ccm, httpParams); } /** * Create the default HTTP protocol parameters. */ private static final HttpParams createHttpParams() { final HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT); HttpConnectionParams.setSoTimeout(params, TIMEOUT); HttpConnectionParams.setSocketBufferSize(params, 8192); ConnManagerParams.setTimeout(params, TIMEOUT); ConnManagerParams.setMaxTotalConnections(params, MAX_CONNECTION); ConnManagerParams.setMaxConnectionsPerRoute(params, CONN_PER_ROUTE); return params; } /** The default maximum number of connections allowed per host */ private static final ConnPerRoute CONN_PER_ROUTE = new ConnPerRoute() { public int getMaxForRoute(HttpRoute route) { return MAX_CONNECTIONS_PER_ROUTE; } }; }