我认为我的代码非常有效。唯一的问题是antoherPlace/submit
根本没有任何文件。
它停留在while循环中,将数据发送到dataStream
,所以我认为这是正确的,但是它没有将文件发送到POST请求。
所以我认为这有问题:
// Read PDF file and send to the another place
InputStream in = url.openStream();
while((bufferLength = in.read(buffer)) != -1) {
dataStream.write(buffer, 0, bufferLength);
}
dataStream.flush();`
完整代码
public void loadPDF() {
try {
URL url = new URL("http://www.pdf995.com/samples/pdf.pdf");
// Init
byte[] buffer = new byte[1024];
int bufferLength;
try {
URLConnection con = url.openConnection();
// Content is PDF
if(con.getContentType().equalsIgnoreCase("application/pdf")) {
// Another Place submit url
String anotherPlace = "https://anotherPlace/submit";
// Send data
HttpURLConnection conn = (HttpURLConnection) new URL(anotherPlace).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setUseCaches(false);
// creates a unique boundary based on time stamp
String boundary = "===" + System.currentTimeMillis() + "===";
conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
conn.setRequestProperty("User-Agent", "Test Agent");
// Write File data to the stream
DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream());
// Read PDF file and send to the another place
InputStream in = url.openStream();
while((bufferLength = in.read(buffer)) != -1) {
dataStream.write(buffer, 0, bufferLength);
}
dataStream.flush();
// Close connections
rd.close();
in.close();
dataStream.close();
}
任何想法可能是什么问题?