1.如果你使用Android studio 开发的话 并且你的api版本是,21以上的话 HttpClient 这个是过时的方法 不会被识别 需要在buile.gradle里面添加:
compile 'org.apache.httpcomponents:httpcore:4.4.5'
2.解决以上问题.具体代码如下:
/** * 请求地址:api/Mobile/uploadPic * 请求类型:post * 必须参数:pic,文件域键名 */ private CommResult uploadPic(String imagepath) { Log.d(TAG, "图片本地地址:" + (uploadIndex + 1) + " " + imagepath); if (!isNetworkConnected(mContext)) { ToastUtils.showShort(mContext, "无网络链接!"); return null; } Gson gson = new Gson(); if (imagepath == null || imagepath.equals("")) { return null; } String url = null; url = "http://" + BaseApplication.getInstance().mUtil.getArea() + "/api/Mobile/uploadPic"; // url = url.replace(" ", "%20"); // 判断图片路径是否存在 if (!FileUtils.isFileExist(imagepath, true)) { Log.d(TAG, "不存在的图片:" + imagepath); mHandler.sendEmptyMessage(0); return null; } HttpClient httpclient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httppost = new HttpPost(url); httppost.addHeader("TOKEN", BaseApplication.getInstance().mUtil.getToken()); int responsecode; String Response = null; try { MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("pic", new FileBody(new File(imagepath))); Log.d(TAG, "entity======" + entity.toString()); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); responsecode = response.getStatusLine().getStatusCode(); if (responsecode == 200) { HttpEntity resEntity = response.getEntity(); Response = EntityUtils.toString(resEntity); } } catch (Exception e) { System.out.println("上传出错啦!"); mHandler.sendEmptyMessage(0); e.printStackTrace(); } if (Response != null) { Log.d(TAG, "end=========" + (uploadIndex + 1) + "张图"); Log.d(TAG, "图片上传成功后结果===========" + (uploadIndex + 1) + " " + Response); // 构造gson, 把服务器端传过来的 json 字符串转化为 java 对象 result = gson.fromJson(Response, CommResult.class); mHandler.sendEmptyMessage(1); } else { mHandler.sendEmptyMessage(0); } return result; }3.以上就是完成图片的上传,但是有的时候需要连续上传 一张然后上传第二张
我用的是thread开启线程 上传之后使用handler进行处理 然后开启第二个线程thread2 奇怪的是thread1 不可以被重复使用 就被报之前的线程在进行 这个不能start 所有只好复制第二个thread2 ,并且这样传到服务器端的照片 是会重复 起先认为我是线程之间的开启有问题 图片的路径传递错误 各种打印均没有问题 只好在第二个线程开启的时候 sleep 1秒
Thread thread2 = new Thread(new Runnable() { @Override public void run() { if (Looper.myLooper()==null) Looper.prepare(); try { Thread.sleep(SLEEPTIME); } catch (InterruptedException e) { e.printStackTrace(); } postFile(list.get(uploadIndex).getImg(), urlupload); // uploadPic(list.get(uploadIndex).getImg()); Looper.loop(); } });为什么要线程休眠1秒 我也不知道 大神指教