我无法将pdf文件发送到服务器。我正在使用AsyncTask 我的代码:
@Override
protected Void doInBackground(Void... params) {
HttpURLConnection conn = null;
int maxBufferSize = 1024;
try {
URL url = new URL(url_path);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setChunkedStreamingMode(1024);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data");
OutputStream outputStream = conn.getOutputStream();
InputStream inputStream = c.getContentResolver().openInputStream(path);
int bytesAvailable = inputStream.available();
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
但是我想发送pdf文件和更多参数。 PDF文件密钥“文件”。帮帮我
答案 0 :(得分:0)
您可以使用Retrofit
和Multipart.part
将任何类型的文件发送到rest API。
答案 1 :(得分:0)
创建类AndroidMultiPartEntity
,
public class AndroidMultiPartEntity extends MultipartEntity {
private final ProgressListener listener;
public AndroidMultiPartEntity(final ProgressListener listener) {
super();
this.listener = listener;
}
public AndroidMultiPartEntity(final HttpMultipartMode mode,
final ProgressListener listener) {
super(mode);
this.listener = listener;
}
public AndroidMultiPartEntity(HttpMultipartMode mode, final String boundary,
final Charset charset, final ProgressListener listener) {
super(mode, boundary, charset);
this.listener = listener;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream, this.listener));
}
public static interface ProgressListener {
void transferred(long num);
}
public static class CountingOutputStream extends FilterOutputStream {
private final ProgressListener listener;
private long transferred;
public CountingOutputStream(final OutputStream out,
final ProgressListener listener) {
super(out);
this.listener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
this.transferred += len;
this.listener.transferred(this.transferred);
}
public void write(int b) throws IOException {
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}
}}
另一个课程UploadFileToServer
public class UploadFileToServer extends AsyncTask<Void, Integer, String> {
private long totalSize = 0;
private Context context;
private String url;
private ImageUploadCallBackListener listener;
private UploadFileModel uploadFileModel;
private boolean isError = false;
private int statusCode = 400;
public UploadFileToServer(Context context, UploadFileModel uploadFileModel, String url, ImageUploadCallBackListener listener) {
this.context = context;
this.uploadFileModel = uploadFileModel;
this.url = url;
this.listener = listener;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... progress) {
}
@Override
protected String doInBackground(Void... voids) {
return uploadFile();
}
@SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
new AndroidMultiPartEntity.ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
if (uploadFileModel.isBitmap()) {
// Adding file data to http body
entity.addPart(uploadFileModel.getContainer(), new ByteArrayBody(Utils.getBytesFromBitmap(context, uploadFileModel.getFileBitmap()), "image/jpeg", String.valueOf(System.currentTimeMillis()) + ".jpg"));
} else if (uploadFileModel.getFileList() != null && uploadFileModel.getFileList().size() > 0) {
for (int i = 0; i < uploadFileModel.getFileList().size(); i++) {
entity.addPart(uploadFileModel.getContainer(), new FileBody(uploadFileModel.getFileList().get(i)));
}
} else {
entity.addPart(uploadFileModel.getContainer(), new FileBody(new File(uploadFileModel.getFilePath())));
}
totalSize = entity.getContentLength();
httppost.addHeader(WebserviceConstant.WS_AUTHORIZATION, PrefHelper.getInstance().getString(PrefHelper.TAG_HEADER_TOKEN, WebserviceConstant.WS_HEADER_TOKEN));
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
statusCode = response.getStatusLine().getStatusCode();
if (statusCode == RestClient.SUCCESS_CODE) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred!";
isError = true;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
isError = true;
} catch (IOException e) {
responseString = e.toString();
isError = true;
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (isError) {
listener.failure(result, statusCode);
} else {
listener.success(result);
}
}
public interface ImageUploadCallBackListener {
public void success(String response);
public void failure(String failure, int statusCode);
}}
在任何需要的地方使用
UploadFileToServer uploadFileToServer = new UploadFileToServer(context, uploadFileModel, postUrl,
new UploadFileToServer.ImageUploadCallBackListener() {
@Override
public void success(String response) {
// success code
}
@Override
public void failure(String failure, int statusCode) {
// failure code
}
});
uploadFileToServer.execute();
我创建了用于图像上传的此类,您可以根据需要进行更改。