【发布时间】:2015-11-04 13:21:50
【问题描述】:
从 Android 5.1 开始,HttpPost 和 HttpMultipart 类已被弃用。现在发出包含文件发送和发布参数的 POST 请求的正确方法是什么?工作示例代码将不胜感激。
另外,如果我们需要在 libs 文件夹中添加任何第三方库,请说明。
【问题讨论】:
标签: android http-post android-5.1.1-lollipop
从 Android 5.1 开始,HttpPost 和 HttpMultipart 类已被弃用。现在发出包含文件发送和发布参数的 POST 请求的正确方法是什么?工作示例代码将不胜感激。
另外,如果我们需要在 libs 文件夹中添加任何第三方库,请说明。
【问题讨论】:
标签: android http-post android-5.1.1-lollipop
是的 Http Client 已弃用,您可以使用 HttpURLConnection。
例子:
private void uploadMultipartData() throws UnsupportedEncodingException
{
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("fileToUpload", new FileBody(uploadFile));
reqEntity.addPart("uname", new StringBody("MyUserName"));
reqEntity.addPart("pwd", new StringBody("MyPassword"));
String response = multipost(server_url, reqEntity);
Log.e("", "Response :" + response);
}
private String multipost(String urlString, MultipartEntity reqEntity)
{
try
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Content-length", reqEntity.getContentLength() + "");
conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
reqEntity.writeTo(conn.getOutputStream());
os.close();
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
return readStream(conn.getInputStream());
}
}
catch (Exception e)
{
Log.e("MainActivity", "multipart post error " + e + "(" + urlString + ")");
}
return null;
}
private String readStream(InputStream in)
{
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try
{
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return builder.toString();
}
【讨论】:
conn.connect();。也删除它。完全在错误的地方。它现在没有伤害。