try { HttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(URL); httpClient.getParams().setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); File f = null; FileBody fo = null; MultipartEntity reqEntity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE); f = new File("/mnt/sdcard/a.png"); fo = new FileBody(f); reqEntity.addPart("uploaded", fo); Log.i("uploaded", "image added Parameter added"); postRequest.setEntity(reqEntity); HttpResponse response = httpClient.execute(postRequest); BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8")); String sResponse; StringBuilder s = new StringBuilder(); while ((sResponse = reader.readLine()) != null) { s = s.append(sResponse); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
用於文件批量上傳等MultipartEntity及http的使用html
/** * 發送文件和基礎數據 * * @param netpath * @return */ public boolean sendForm(String netpath) { String path = netpath; boolean res = false; try { HttpPost httpPost = new HttpPost(path); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder .create(); // 設置爲瀏覽器兼容模式 entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // 設置請求的編碼格式 // entityBuilder.setCharset(Charset.forName(HTTP.UTF_8)); entityBuilder.setCharset(Charset.forName(HTTP.UTF_8)); for (KeyValue keyValue : beanData.getKeyvalues()) { entityBuilder.addTextBody( keyValue.getKey(), keyValue.getValue(), ContentType.create("text/plain", Charset.forName(this.charset))); } for (int i = 0; i < values.size(); i++) { entityBuilder.addBinaryBody("file", new File(values.get(i))); } httpPost.setEntity(entityBuilder.build()); // httpPost.setHeader("Content-type", "text/html;charset=UTF-8"); HttpResponse response = new DefaultHttpClient().execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { res = true; resultString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return res; }