我对 Jakarta Commons HttpClient 有疑问。在我自己编写的 HttpServer 得到真正的请求之前,有一个请求是完全空的。这是第一个问题。 第一个问题解决了。这是由不必要的 URLConnection 引起的! 第二个问题是,有时请求数据在http请求的第三或第四行之后结束:
POST / HTTP/1.1
User-Agent: Jakarta Commons-HttpClient/3.1
Host: 127.0.0.1:4232
对于调试,我使用的是 Axis TCPMonitor。那里一切都很好,但空请求。
我如何处理流:
StringBuffer requestBuffer = new StringBuffer();
InputStreamReader is = new InputStreamReader(socket.getInputStream(), "UTF-8");
int byteIn = -1;
do {
byteIn = is.read();
if (byteIn > 0) {
requestBuffer.append((char) byteIn);
}
} while (byteIn != -1 && is.ready());
String requestData = requestBuffer.toString();
找到了一种处理流的新方法。我读取了所有标题参数并使用“内容长度”来读取帖子数据。
InputStream is = mySocket.getInputStream();
if (is == null) {
return;
}
BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// Read the request line
// ...
// ...
// Parse the header
Properties header = new Properties();
if (st.hasMoreTokens()) {
String line = in.readLine();
while (line != null && line.trim().length() > 0) {
int p = line.indexOf(':');
header.put(line.substring(0, p).trim().toLowerCase(), line.substring(p + 1).trim());
line = in.readLine();
}
}
// If the method is POST, there may be parameters
// in data section, too, read it:
String postLine = "";
if (method.equalsIgnoreCase("POST")) {
long size = 0x7FFFFFFFFFFFFFFFl;
String contentLength = header.getProperty("content-length");
if (contentLength != null) {
try {
size = Integer.parseInt(contentLength);
} catch (NumberFormatException ex) {
}
}
postLine = "";
char buf[] = new char[512];
int read = in.read(buf);
while (read >= 0 && size > 0 && !postLine.endsWith("\r\n")) {
size -= read;
postLine += String.valueOf(buf, 0, read);
if (size > 0) {
read = in.read(buf);
}
}
postLine = postLine.trim();
decodeParms(postLine, parms);
}
我如何发送请求:
client.getParams().setSoTimeout(30000);
method = new PostMethod(url.getPath());
method.getParams().setContentCharset("utf-8");
method.setRequestHeader("Content-Type", "application/xml; charset=utf-8");
method.addRequestHeader("Connection", "close");
method.setFollowRedirects(false);
byte[] requestXml = getRequestXml();
method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(requestXml)));
client.executeMethod(method);
int statusCode = method.getStatusCode();
有没有人知道如何解决这些问题?
亚历克斯