public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, File file, Map<String, String> mStringPart) { super(Method.POST, url, errorListener); this.mListener = listener; this.mFilePart = file; this.mStringPart = mStringPart; entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); try { entity.setCharset(CharsetUtils.get("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } buildMultipartEntity(); httpentity = entity.build(); }
@Deprecated public static String uploadFileFromPath(String requestUrl, String requestMethod, String filePath) throws ClientProtocolException, IOException{ String result = null; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(requestUrl); // 把文件转换成流对象FileBody File file = new File(filePath); FileBody media = new FileBody(file); /*StringBody uploadFileName = new StringBody("my.png", ContentType.create("text/plain", Consts.UTF_8));*/ // 以浏览器兼容模式运行,防止文件名乱码。 HttpEntity reqEntity = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addPart("file", media) // media对应服务端类的同名属性<File类型> .setCharset(CharsetUtils.get("UTF-8")).build(); httpPost.setEntity(reqEntity); // 发起请求 并返回请求的响应 CloseableHttpResponse response = httpClient.execute(httpPost); try { // 获取响应对象 HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, Charset.forName("UTF-8")); } // 销毁 EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpClient.close(); } return result; }
@SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); this.credentialsCharset = CharsetUtils.get(in.readUTF()); if (this.credentialsCharset == null) { this.credentialsCharset = Consts.ASCII; } this.challengeState = (ChallengeState) in.readObject(); }
/** * Converts a Map to a UrlEncodedFormEntity. * @param map The Map to convert. Not {@code null}. * @return UrlEncodedFormEntity */ public static UrlEncodedFormEntity mapToUrlEncodedFormEntity(Map<String, String> map) { List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); for (String key : map.keySet()) urlParameters.add(new BasicNameValuePair(key, map.get(key))); try { return new UrlEncodedFormEntity(urlParameters, CharsetUtils.get(UTF8)); } catch (UnsupportedEncodingException ignored) { return null; } }