我创建了一个简单的UrlConnection并使用post-method。当我查看wireshark时,一切都发送给我。我尝试将响应存储到字符串中。并且该字符串是整个数据包的简短版本,当它正确关闭时(带有/ html标记)。
记事本中的差异让我这样:
<a href="wato.py?mode=..."></a>
并在wireshark中:
<a href="wato.py?mode=edithost&host=ColorPrinter ... muchmuchmore ...
这是它似乎得到削减的地方
真的很奇怪,现在这是我的代码:
public void uploadCsv(File csvFile) throws CsvImportException, IOException {
String sUrl = String.format(urlBaseWato, hostAddress);
String csvFileContent = readFile(csvFile);
ParamContainer params = new ParamContainer().addParam("a", "a")
.addParam("b", b)
.addParam("c", "c");
URLConnection connection = new URL(sUrl).openConnection();
postData(connection, params);
String resp = getResponse(connection); // <---- broken string here :(
...
}
-
private void postData(URLConnection con, ParamContainer params) throws IOException {
int cLen = params.getEncodedParamString().getBytes().length;
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches (false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Cookie", authCookie.toString());
con.setRequestProperty("Content-Length", Integer.toString(cLen));
//Send request
DataOutputStream os = new DataOutputStream (con.getOutputStream());
os.writeBytes(params.getEncodedParamString());
os.flush ();
os.close ();
}
-
private String getResponse(URLConnection connection) throws IOException {
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
String response = "";
while ((line = in.readLine()) != null)
response +=line;
in.close();
return response;
}
神秘,我没有丝毫想法。你能救我吗?
答案 0 :(得分:1)
使用IOUtils
有帮助吗?
URLConnection connection = new URL(sUrl).openConnection();
IOUtils.toString(connection.getInputStream(), "UTF-8");
甚至:
IOUtils.toString(new URL(sUrl), "UTF-8");
即使没有,也要先考虑减少代码中的样板量。
答案 1 :(得分:0)
我想如果这是问题并且可以接受,我应该做出这个答案。我已经看到关闭套接字切断已经写入的流的情况。尝试将Thread.sleep(5000)放在套接字闭包之前。