Android studio 开发
导入了 org.apache.httpcomponents:httpmime:4.5.1在使用httpClient上传文件时报错,找不到ContentType这个类 /**
* 本方法需要导入httpmime的jar包
* @param urlPath 请求路径
* @param params 上传参数
* @param files 上传文件的本地路径
* @return 服务器返回结果
* @throws IOException
*/
public static String doPostByHttpClient(String urlPath, Map<String, Object> params, Map<String, String> files) throws IOException {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlPath);
MultipartEntity mpEntity = new MultipartEntity();
for (Map.Entry<String, String> file : files.entrySet()) {
ContentBody cbFile = new FileBody(new File(file.getValue()));
mpEntity.addPart(file.getKey(), cbFile);
}
for (Map.Entry<String, Object> entry : params.entrySet()) {
mpEntity.addPart(entry.getKey(), new StringBody((String) entry.getValue(), "text/plain", Charset.forName("UTF-8")));
}
post.setEntity(mpEntity);
String res = null;
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
res = getStringFromStream(response.getEntity().getContent());
}
String content = EntityUtils.toString(response.getEntity());
client.getConnectionManager().shutdown();
return res;
}
导入了 org.apache.httpcomponents:httpmime:4.5.1在使用httpClient上传文件时报错,找不到ContentType这个类 /**
* 本方法需要导入httpmime的jar包
* @param urlPath 请求路径
* @param params 上传参数
* @param files 上传文件的本地路径
* @return 服务器返回结果
* @throws IOException
*/
public static String doPostByHttpClient(String urlPath, Map<String, Object> params, Map<String, String> files) throws IOException {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlPath);
MultipartEntity mpEntity = new MultipartEntity();
for (Map.Entry<String, String> file : files.entrySet()) {
ContentBody cbFile = new FileBody(new File(file.getValue()));
mpEntity.addPart(file.getKey(), cbFile);
}
for (Map.Entry<String, Object> entry : params.entrySet()) {
mpEntity.addPart(entry.getKey(), new StringBody((String) entry.getValue(), "text/plain", Charset.forName("UTF-8")));
}
post.setEntity(mpEntity);
String res = null;
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
res = getStringFromStream(response.getEntity().getContent());
}
String content = EntityUtils.toString(response.getEntity());
client.getConnectionManager().shutdown();
return res;
}
项目module/build.gradle android下面添加
android {
useLibrary = 'org.apache.http.legacy'
}如果不行的话
在dependencies中添加
dependencies {
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}