随着Android 5.1的发布,看起来所有Apache http的东西都被弃用了.看文档是没用的; 他们都说
This class was deprecated in API level 22.
Please use openConnection() instead. Please visit this webpage for further details.
这是第一次阅读它时没关系,但是当每个被弃用的类都说明了这一点时,它没那么有用.
总之,什么是类的替代喜欢HttpEntity,特别是StringEntity和MultipartEntity?我替换BasicNameValuePair了我自己的Android Pair<T, S>类实现,它看起来URLEncoder.encode是一个很好的替代品URLEncodedUtils,但我不知道该怎么做HttpEntity.
编辑
我决定重新编写网络内容.要尝试使用Retrofit和OkHttp
编辑
认真看看将你的通话和东西转换为Retrofit.很漂亮.我很高兴我做到了.有一些障碍,但它很酷.
我正在尝试将图像发送到我的API.但是在使用MultipartEntity StringBody时我得到错误,因为不推荐使用StringBody(String).
我不工作.我是Android的一个示例,通过MultipartEntity将图像发送到服务器 - 设置内容类型?.
这是代码:
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("api_key", api_key));
params.add(new BasicNameValuePair("access_token", access_token));
API api = new API(mApiKey, mApiSecret);
HttpClient client = new DefaultHttpClient();
HttpPost postMethod = new HttpPost("MY API URL");
File file = new File(imagePath);
MultipartEntity entity = new MultipartEntity();
FileBody contentFile = new FileBody(file);
StringBody api_key = new StringBody(mApiKey);
StringBody access_token = new StringBody(access_token);
entity.addPart("api_key", api_key);
entity.addPart("hash", access_token);
entity.addPart("image", contentFile);
postMethod.setEntity(entity);
client.execute(postMethod);
} catch (Exception e) {
e.printStackTrace(); …Run Code Online (Sandbox Code Playgroud) 我在这里使用答案尝试POST通过数据上传发出请求,但我从服务器端有不寻常的要求.该服务器是一个PHP脚本,需要filename对Content-Disposition行,因为它是期待一个文件上传.
Content-Disposition: form-data; name="file"; filename="-"
Run Code Online (Sandbox Code Playgroud)
但是,在客户端,我想发布一个内存缓冲区(在这种情况下是一个String)而不是一个文件,但让服务器处理它就好像它是一个文件上传.
但是,使用StringBody我无法在行filename上添加必填字段Content-Disposition.因此,我试图使用FormBodyPart,但这只是filename在一个单独的行.
HttpPost httppost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
ContentBody body = new StringBody(data,
org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM);
FormBodyPart fbp = new FormBodyPart("file", body);
fbp.addField("filename", "-");
entity.addPart(fbp);
httppost.setEntity(entity);
Run Code Online (Sandbox Code Playgroud)
如果没有先将我写入文件然后再将其读回来,我怎样才能filename进入该Content-Disposition行String?