上传文件之至客户端处理http请求

来源:互联网 发布:一个爱心的软件 编辑:程序博客网 时间:2024/06/05 08:52


Android客户端主要代码:

 

public ImageHttp(Context context) {super(context);filePath = context.getCacheDir().getAbsolutePath();}public void uploadUserImg(Bitmap bitmap,IHttpSenderCallBack<String> callback) {this.callback = callback;File file = getFile(bitmap);// 注意与服务端协商if (file == null) {return;}List<Parameter> parameters = new ArrayList<Parameter>();parameters.add(new Parameter("file", file));uploadFile("uploadImg", parameters);}private File getFile(Bitmap bitmap) {File file = null;String path = filePath + "/image.jpg";if (bitmap != null && !StringUtil.emptyOrNull(path)) {try {FileOutputStream out = new FileOutputStream(path);bitmap.compress(Bitmap.CompressFormat.JPEG, 60, out);out.flush();out.close();file = new File(path);} catch (FileNotFoundException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}return file;}


 

protected String uploadFile(String methodName, List<Parameter> parameter) {String errorMsg = "";try {String serviceUrl = getPostUrl(methodName);HttpPost httpPost = new HttpPost(serviceUrl);//采用http4包,不需要再添加  multipart/form-data表单 ,切记,这儿耽搁了好久MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // 文件传输if (parameter != null && !parameter.isEmpty()) {for (int i = 0; i < parameter.size(); i++) {Parameter p = parameter.get(i);if ("file".equals(p.getKey())) {mpEntity.addPart(p.getKey(),new FileBody(((File) p.getValue())));} else {mpEntity.addPart(p.getKey(), new StringBody(p.getValue().toString()));}}httpPost.setEntity(mpEntity);}HttpClient httpclient = new DefaultHttpClient();httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT);httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT);HttpResponse httpResponse = httpclient.execute(httpPost);String result = "";int status = httpResponse.getStatusLine().getStatusCode();LogUtil.d("httpResponseCode--------->" + status);if (status == HttpStatus.SC_OK) {result = EntityUtils.toString(httpResponse.getEntity());}parseProperty_(result, methodName);result = "";} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}return errorMsg;}


 

0 0