Android Http请求图片上传工具类

 
  1. import java.io.ByteArrayOutputStream;
  2. import java.io.DataOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.net.HttpURLConnection;
  9. import java.net.MalformedURLException;
  10. import java.net.Socket;
  11. import java.net.URL;
  12. import java.net.UnknownHostException;
  13. import java.security.KeyManagementException;
  14. import java.security.KeyStore;
  15. import java.security.KeyStoreException;
  16. import java.security.NoSuchAlgorithmException;
  17. import java.security.UnrecoverableKeyException;
  18. import java.util.ArrayList;
  19. import java.util.HashMap;
  20. import java.util.Map;
  21. import java.util.UUID;
  22. import javax.net.ssl.SSLContext;
  23. import javax.net.ssl.TrustManager;
  24. import javax.net.ssl.X509TrustManager;
  25. import org.apache.http.Header;
  26. import org.apache.http.HttpEntity;
  27. import org.apache.http.HttpResponse;
  28. import org.apache.http.HttpStatus;
  29. import org.apache.http.HttpVersion;
  30. import org.apache.http.client.HttpClient;
  31. import org.apache.http.client.entity.UrlEncodedFormEntity;
  32. import org.apache.http.client.methods.HttpGet;
  33. import org.apache.http.client.methods.HttpPost;
  34. import org.apache.http.conn.ClientConnectionManager;
  35. import org.apache.http.conn.ConnectTimeoutException;
  36. import org.apache.http.conn.params.ConnManagerParams;
  37. import org.apache.http.conn.scheme.PlainSocketFactory;
  38. import org.apache.http.conn.scheme.Scheme;
  39. import org.apache.http.conn.scheme.SchemeRegistry;
  40. import org.apache.http.conn.ssl.SSLSocketFactory;
  41. import org.apache.http.impl.client.DefaultHttpClient;
  42. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  43. import org.apache.http.message.BasicHeader;
  44. import org.apache.http.message.BasicNameValuePair;
  45. import org.apache.http.params.BasicHttpParams;
  46. import org.apache.http.params.HttpConnectionParams;
  47. import org.apache.http.params.HttpParams;
  48. import org.apache.http.params.HttpProtocolParams;
  49. import org.apache.http.protocol.HTTP;
  50. import org.apache.http.util.EntityUtils;
  51. import android.content.Context;
  52. import android.net.ConnectivityManager;
  53. import android.net.NetworkInfo;
  54. import android.util.Log;
  55. import android.widget.Toast;
  56. /**
  57. * HttpUtil Class Capsule Most Functions of Http Operations
  58. *
  59. * @author sfshine
  60. *
  61. */
  62. public HttpUtil {
  63. private static Header[] headers = new BasicHeader[1];
  64. private static String TAG = "HTTPUTIL";
  65. private static int TIMEOUT = 5 * 1000;
  66. private static final String BOUNDARY = "---------------------------7db1c523809b2";
  67. /**
  68. * Your header of http op
  69. *
  70. * @return
  71. */
  72. static {
  73. headers[0] = new BasicHeader("User-Agent",
  74. "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
  75. }
  76. public static boolean delete(String murl) throws Exception {
  77. URL url = new URL(murl);
  78. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  79. conn.setRequestMethod("DELETE");
  80. conn.setConnectTimeout(5000);
  81. if (conn.getResponseCode() == 204) {
  82. MLog.e(conn.toString());
  83. return true;
  84. }
  85. MLog.e(conn.getRequestMethod());
  86. MLog.e(conn.getResponseCode() + "");
  87. return false;
  88. }
  89. /**
  90. * Op Http get request
  91. *
  92. * @param url
  93. * @param map
  94. * Values to request
  95. * @return
  96. */
  97. static public String get(String url) {
  98. return get(url, null);
  99. }
  100. static public String get(String url, HashMap<String, String> map) {
  101. HttpClient client = getNewHttpClient();
  102. HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
  103. HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
  104. ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
  105. String result = "ERROR";
  106. if (null != map) {
  107. int i = 0;
  108. for (Map.Entry<String, String> entry : map.entrySet()) {
  109. Log.i(TAG, entry.getKey() + "=>" + entry.getValue());
  110. if (i == 0) {
  111. url = url + "?" + entry.getKey() + "=" + entry.getValue();
  112. } else {
  113. url = url + "&" + entry.getKey() + "=" + entry.getValue();
  114. }
  115. i++;
  116. }
  117. }
  118. HttpGet get = new HttpGet(url);
  119. get.setHeaders(headers);
  120. Log.i(TAG, url);
  121. try {
  122. HttpResponse response = client.execute(get);
  123. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  124. // setCookie(response);
  125. result = EntityUtils.toString(response.getEntity(), "UTF-8");
  126. } else {
  127. result = EntityUtils.toString(response.getEntity(), "UTF-8")
  128. + response.getStatusLine().getStatusCode() + "ERROR";
  129. }
  130. } catch (ConnectTimeoutException e) {
  131. result = "TIMEOUTERROR";
  132. }
  133. catch (Exception e) {
  134. result = "OTHERERROR";
  135. e.printStackTrace();
  136. }
  137. Log.i(TAG, "result =>" + result);
  138. return result;
  139. }
  140. /**
  141. * Op Http post request , "404error" response if failed
  142. *
  143. * @param url
  144. * @param map
  145. * Values to request
  146. * @return
  147. */
  148. static public String post(String url, HashMap<String, String> map) {
  149. HttpClient client = getNewHttpClient();
  150. HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
  151. HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
  152. ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
  153. HttpPost post = new HttpPost(url);
  154. MLog.i(TAG, url);
  155. post.setHeaders(headers);
  156. String result = "ERROR";
  157. ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
  158. if (map != null) {
  159. for (Map.Entry<String, String> entry : map.entrySet()) {
  160. Log.i(TAG, entry.getKey() + "=>" + entry.getValue());
  161. BasicNameValuePair pair = new BasicNameValuePair(
  162. entry.getKey(), entry.getValue());
  163. pairList.add(pair);
  164. }
  165. }
  166. try {
  167. HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
  168. post.setEntity(entity);
  169. HttpResponse response = client.execute(post);
  170. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  171. result = EntityUtils.toString(response.getEntity(), "UTF-8");
  172. } else {
  173. result = EntityUtils.toString(response.getEntity(), "UTF-8")
  174. + response.getStatusLine().getStatusCode() + "ERROR";
  175. }
  176. } catch (ConnectTimeoutException e) {
  177. result = "TIMEOUTERROR";
  178. }
  179. catch (Exception e) {
  180. result = "OTHERERROR";
  181. e.printStackTrace();
  182. }
  183. Log.i(TAG, "result =>" + result);
  184. return result;
  185. }
  186. /**
  187. * 自定义的http请求可以设置为DELETE PUT等而不是GET
  188. *
  189. * @param url
  190. * @param params
  191. * @param method
  192. * @throws IOException
  193. */
  194. public static String customrequest(String url,
  195. HashMap<String, String> params, String method) {
  196. try {
  197. URL postUrl = new URL(url);
  198. HttpURLConnection conn = (HttpURLConnection) postUrl
  199. .openConnection();
  200. conn.setDoOutput(true);
  201. conn.setDoInput(true);
  202. conn.setConnectTimeout(5 * 1000);
  203. conn.setRequestMethod(method);
  204. conn.setUseCaches(false);
  205. conn.setInstanceFollowRedirects(true);
  206. conn.setRequestProperty("Content-Type",
  207. "application/x-www-form-urlencoded");
  208. conn.setRequestProperty("User-Agent",
  209. "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
  210. conn.connect();
  211. OutputStream out = conn.getOutputStream();
  212. StringBuilder sb = new StringBuilder();
  213. if (null != params) {
  214. int i = params.size();
  215. for (Map.Entry<String, String> entry : params.entrySet()) {
  216. if (i == 1) {
  217. sb.append(entry.getKey() + "=" + entry.getValue());
  218. } else {
  219. sb.append(entry.getKey() + "=" + entry.getValue() + "&");
  220. }
  221. i--;
  222. }
  223. }
  224. String content = sb.toString();
  225. out.write(content.getBytes("UTF-8"));
  226. out.flush();
  227. out.close();
  228. InputStream inStream = conn.getInputStream();
  229. String result = inputStream2String(inStream);
  230. Log.i(TAG, "result>" + result);
  231. conn.disconnect();
  232. return result;
  233. } catch (Exception e) {
  234. // TODO: handle exception
  235. }
  236. return null;
  237. }
  238. /**
  239. * 必须严格限制get请求所以增加这个方法 这个方法也可以自定义请求
  240. *
  241. * @param url
  242. * @param method
  243. * @throws Exception
  244. */
  245. public static String customrequestget(String url,
  246. HashMap<String, String> map, String method) {
  247. if (null != map) {
  248. int i = 0;
  249. for (Map.Entry<String, String> entry : map.entrySet()) {
  250. if (i == 0) {
  251. url = url + "?" + entry.getKey() + "=" + entry.getValue();
  252. } else {
  253. url = url + "&" + entry.getKey() + "=" + entry.getValue();
  254. }
  255. i++;
  256. }
  257. }
  258. try {
  259. URL murl = new URL(url);
  260. System.out.print(url);
  261. HttpURLConnection conn = (HttpURLConnection) murl.openConnection();
  262. conn.setConnectTimeout(5 * 1000);
  263. conn.setRequestMethod(method);
  264. conn.setRequestProperty("User-Agent",
  265. "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
  266. InputStream inStream = conn.getInputStream();
  267. String result = inputStream2String(inStream);
  268. Log.i(TAG, "result>" + result);
  269. conn.disconnect();
  270. return result;
  271. } catch (Exception e) {
  272. // TODO: handle exception
  273. }
  274. return null;
  275. }
  276. /**
  277. * 上传多张图片
  278. */
  279. public static String post(String actionUrl, Map<String, String> params,
  280. Map<String, File> files) {
  281. String BOUNDARY = java.util.UUID.randomUUID().toString();
  282. String PREFIX = "--", LINEND = "";
  283. String MULTIPART_FROM_DATA = "multipart/form-data";
  284. String CHARSET = "UTF-8";
  285. try {
  286. URL uri = new URL(actionUrl);
  287. HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
  288. conn.setReadTimeout(5 * 1000); // 缓存的最长时间
  289. conn.setDoInput(true);// 允许输入
  290. conn.setDoOutput(true);// 允许输出
  291. conn.setUseCaches(false); // 不允许使用缓存
  292. conn.setRequestMethod("POST");
  293. conn.setRequestProperty("connection", "keep-alive");
  294. conn.setRequestProperty("Charsert", "UTF-8");
  295. conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
  296. + ";boundary=" + BOUNDARY);
  297. // 首先组拼文本类型的参数
  298. StringBuilder sb = new StringBuilder();
  299. for (Map.Entry<String, String> entry : params.entrySet()) {
  300. sb.append(PREFIX);
  301. sb.append(BOUNDARY);
  302. sb.append(LINEND);
  303. sb.append("Content-Disposition: form-data; name=""
  304. + entry.getKey() + """ + LINEND);
  305. sb.append("Content-Type: text/plain; charset=" + CHARSET
  306. + LINEND);
  307. sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
  308. sb.append(LINEND);
  309. sb.append(entry.getValue());
  310. sb.append(LINEND);
  311. }
  312. DataOutputStream outStream = new DataOutputStream(
  313. conn.getOutputStream());
  314. outStream.write(sb.toString().getBytes());
  315. InputStream in = null;
  316. // 发送文件数据
  317. if (files != null) {
  318. for (Map.Entry<String, File> file : files.entrySet()) {
  319. StringBuilder sb1 = new StringBuilder();
  320. sb1.append(PREFIX);
  321. sb1.append(BOUNDARY);
  322. sb1.append(LINEND);
  323. sb1.append("Content-Disposition: form-data; name=""
  324. + file.getKey() + ""; filename=""
  325. + file.getValue().getName() + """ + LINEND);
  326. sb1.append("Content-Type: image/pjpeg; " + LINEND);
  327. sb1.append(LINEND);
  328. outStream.write(sb1.toString().getBytes());
  329. InputStream is = new FileInputStream(file.getValue());
  330. byte[] buffer = new byte[1024];
  331. int len = 0;
  332. while ((len = is.read(buffer)) != -1) {
  333. outStream.write(buffer, 0, len);
  334. }
  335. is.close();
  336. outStream.write(LINEND.getBytes());
  337. }
  338. // 请求结束标志
  339. byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND)
  340. .getBytes();
  341. outStream.write(end_data);
  342. outStream.flush();
  343. // 得到响应码
  344. int res = conn.getResponseCode();
  345. // if (res == 200) {
  346. in = conn.getInputStream();
  347. int ch;
  348. StringBuilder sb2 = new StringBuilder();
  349. while ((ch = in.read()) != -1) {
  350. sb2.append((char) ch);
  351. }
  352. // }
  353. outStream.close();
  354. conn.disconnect();
  355. return in.toString();
  356. }
  357. } catch (Exception e) {
  358. }
  359. return null;
  360. }
  361. /**
  362. * is转String
  363. *
  364. * @param in
  365. * @return
  366. * @throws IOException
  367. */
  368. public static String inputStream2String(InputStream in) throws IOException {
  369. StringBuffer out = new StringBuffer();
  370. byte[] b = new byte[4096];
  371. for (int n; (n = in.read(b)) != -1;) {
  372. out.append(new String(b, 0, n));
  373. }
  374. return out.toString();
  375. }
  376. /**
  377. * check net work
  378. *
  379. * @param context
  380. * @return
  381. */
  382. public static boolean hasNetwork(Context context) {
  383. ConnectivityManager con = (ConnectivityManager) context
  384. .getSystemService(Context.CONNECTIVITY_SERVICE);
  385. NetworkInfo workinfo = con.getActiveNetworkInfo();
  386. if (workinfo == null || !workinfo.isAvailable()) {
  387. Toast.makeText(context, "当前无网络连接,请稍后重试", Toast.LENGTH_SHORT).show();
  388. return false;
  389. }
  390. return true;
  391. }
  392. /***
  393. * @category check if the string is null
  394. * @return true if is null
  395. * */
  396. public static boolean isNull(String string) {
  397. boolean t1 = "".equals(string);
  398. boolean t2 = string == null;
  399. boolean t3 = string.equals("null");
  400. if (t1 || t2 || t3) {
  401. return true;
  402. } else {
  403. return false;
  404. }
  405. }
  406. static public byte[] getBytes(File file) throws IOException {
  407. InputStream ios = null;
  408. ByteArrayOutputStream ous = null;
  409. try {
  410. byte[] buffer = new byte[4096];
  411. ous = new ByteArrayOutputStream();
  412. ios = new FileInputStream(file);
  413. int read = 0;
  414. while ((read = ios.read(buffer)) != -1) {
  415. ous.write(buffer, 0, read);
  416. }
  417. } finally {
  418. try {
  419. if (ous != null)
  420. ous.close();
  421. } catch (IOException e) {
  422. }
  423. try {
  424. if (ios != null)
  425. ios.close();
  426. } catch (IOException e) {
  427. }
  428. }
  429. return ous.toByteArray();
  430. }
  431. public static MLog {
  432. static public void e(String msg) {
  433. android.util.Log.e("=======ERROR======", msg);
  434. }
  435. static public void e(String tag, String msg) {
  436. android.util.Log.e(tag, msg);
  437. }
  438. static public void i(String msg) {
  439. android.util.Log.i("=======INFO======", msg);
  440. }
  441. static public void i(String tag, String msg) {
  442. android.util.Log.i(tag, msg);
  443. }
  444. }
  445. /**
  446. * 处理https加密失败的情况
  447. *
  448. * @return
  449. */
  450. public static HttpClient getNewHttpClient() {
  451. try {
  452. KeyStore trustStore = KeyStore.getInstance(KeyStore
  453. .getDefaultType());
  454. trustStore.load(null, null);
  455. SSLSocketFactory sf = new HttpUtil.SSLSocketFactoryEx(trustStore);
  456. sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  457. HttpParams params = new BasicHttpParams();
  458. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  459. HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
  460. SchemeRegistry registry = new SchemeRegistry();
  461. registry.register(new Scheme("http", PlainSocketFactory
  462. .getSocketFactory(), 80));
  463. registry.register(new Scheme("https", sf, 443));
  464. ClientConnectionManager ccm = new ThreadSafeClientConnManager(
  465. params, registry);
  466. return new DefaultHttpClient(ccm, params);
  467. } catch (Exception e) {
  468. return new DefaultHttpClient();
  469. }
  470. }
  471. static public SSLSocketFactoryEx extends SSLSocketFactory {
  472. SSLContext sslContext = SSLContext.getInstance("TLS");
  473. public SSLSocketFactoryEx(KeyStore truststore)
  474. throws NoSuchAlgorithmException, KeyManagementException,
  475. KeyStoreException, UnrecoverableKeyException {
  476. super(truststore);
  477. TrustManager tm = new X509TrustManager() {
  478. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  479. return null;
  480. }
  481. @Override
  482. public void checkClientTrusted(
  483. java.security.cert.X509Certificate[] chain,
  484. String authType)
  485. throws java.security.cert.CertificateException {
  486. }
  487. @Override
  488. public void checkServerTrusted(
  489. java.security.cert.X509Certificate[] chain,
  490. String authType)
  491. throws java.security.cert.CertificateException {
  492. }
  493. };
  494. sslContext.init(null, new TrustManager[] { tm }, null);
  495. }
  496. @Override
  497. public Socket createSocket(Socket socket, String host, int port,
  498. boolean autoClose) throws IOException, UnknownHostException {
  499. return sslContext.getSocketFactory().createSocket(socket, host,
  500. port, autoClose);
  501. }
  502. @Override
  503. public Socket createSocket() throws IOException {
  504. return sslContext.getSocketFactory().createSocket();
  505. }
  506. }
  507. }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值