我对Java中的网络编程非常陌生。我正在尝试将.img
文件上传到Netgear路由器以更新固件。但是在第con.getInputStream()
行,我得到了该计划的死亡旋转轮,经过几个小时的等待后没有任何回报。请帮忙。
private void uploadFile(String filePath) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "WebKitFormBoundaryBZGOKkNua1gVYHFA";
try {
URL mUrl = new URL(url);
HttpURLConnection con = (HttpURLConnection) mUrl.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Upgrade-Insecure-Requests", "1");
con.setRequestProperty("Authorization",
"Basic YWRtaW46cGFzc3dvcmQ=");
con.setRequestProperty("Host", "www.routerlogin.net");
con.setRequestProperty("Origin", "http://www.routerlogin.net");
con.setRequestProperty("Referer",
"http://www.routerlogin.net/UPG_upgrade.htm");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "
+ "name=\"mtenFWUpload\";filename=\"" + fileName + "\""
+ end + "Content-Type: application/octet-stream");
ds.writeBytes(end);
FileInputStream fStream = new FileInputStream(filePath);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fStream.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "
+ "name=\"Upgrade\"" + end);
ds.writeBytes("ÉÏ´«");
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; " + "name=\"SID\""
+ end);
ds.writeBytes("");
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
fStream.close();
ds.flush();
InputStream is = con.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
ds.close();
Thread.sleep(2000);
getUpdateKey();
} catch (Exception e) {
e.printStackTrace();
}
}