我需要将文件上传到服务器,我不知道如何执行与此html代码相同的POST请求:
<form enctype="multipart/form-data" method="post" action="https://example.net/api_upload.php">
我通常使用此GET代码,有人可以帮助更改它以发出POST请求吗?我知道我应该更改“setRequestMethod”,但不知道如何设置multipart来上传文件。
JSONArray jsonArray = null;
String jsonString = null;
HttpURLConnection conn = null;
String line;
URL url;
try
{
url = new URL(serviceUrl);
}
catch (MalformedURLException e)
{
throw new IllegalArgumentException("invalid url: " + serviceUrl);
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
// post the request
// handle the response
int status = conn.getResponseCode();
Log.w("getJSONStringWithParam", "Response Status = " + status);
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line + '\n');
}
jsonString = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return jsonString;
谢谢!