我正在尝试使用 连接服务器HttpURLConnection
,但 PUT 方法有问题。
我需要发送一个包含1500 个字符(或更多)的字符串,但在这种情况下,服务器会产生超时并返回500 - server internal error。
如果我发送的字符串少于1400 个字符,我没有问题,服务器返回OK。
我的代码如下:
public String connectToServer(String prototype) {
String responseString = "";
try {
BufferedReader in = new BufferedReader(new InputStreamReader(openURLForInput(new URL(URL), USERNAME, PASSWORD, prototype)));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
responseString += line;
}
} catch (IOException e) {
e.printStackTrace();
responseString = e.toString();
}
return responseString;
}
//-----------------------
public InputStream openURLForInput(URL url, String uname, String pword, String content) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", userNamePasswordBase64(uname, pword)); // I know this is OK
conn.addRequestProperty("Content-type", "application/xml; charset=utf-8");
//conn.setChunkedStreamingMode(8 * 1024);
conn.setRequestMethod("PUT");
conn.connect();
OutputStream output = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(output, "UTF-8");
BufferedWriter writer = new BufferedWriter(osw);
writer.write(content); // content length > 1400 characters
writer.close();
output.close();
int status = conn.getResponseCode();
Log.i("STATUS", status + "");
Log.i("STATUS_ERROR", conn.getResponseMessage());
return conn.getInputStream();
}
我尝试添加线条
conn.setFixedLengthStreamingMode(contentLength)
conn.setChunkedStreamingMode(8 * 1024);
但是无论如何服务器的答案都是错误的。
更新:
我可以检测到问题。出于某种原因,当我尝试在请求中发送大型正文时,服务器会产生超时但不是所有网络,只有一些网络。我使用安全连接 SSL,也许这会带来问题?