是否有人知道Android应用程序充当REST API客户端并允许附加文件?我希望在Postman中做相同的操作,但是来自Android设备:
我在Google Play上尝试过“REST Client for Android”和“HTTP Client”,但这些似乎只允许正文中的文字,而不是文件附件。任何人都可以为Android目前的选项提供建议吗?
答案 0 :(得分:0)
https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server
请找到改造api的上述链接,主要使用restapi。
答案 1 :(得分:0)
使用HttpURLConnection类在服务器上上传图像。
String urlStr= "url link";
String response;
boolean isGetMethod = false;
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
DataOutputStream dataOutputStream;
String lineEnd = "\r\n", twoHyphens = "--", boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
File file;
int maxBufferSize = 1024 * 1024;
FileInputStream fileInputStream;
try {
URL url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
if (!isGetMethod) {
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
file = new File("image file path");
fileInputStream = new FileInputStream(file);
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
dataOutputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
dataOutputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dataOutputStream.flush();
dataOutputStream.close();
}
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder builder = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
builder.append(inputLine);
}
response = builder.toString();
bufferedReader.close();
} else
return response;
} catch (Exception e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
return response;
}
@Override
protected void onPostExecute(String response) {
}
}