URL连接获取InputStream为空问题排查及URL编码修复咨询
问题分析与修复方案
1. URL参数分隔符错误是核心问题
你在代码里构造URL时误用了HTML转义字符&来分隔参数,但Java的URL类会把&当作普通字符串处理,进而在解析时再次转义,导致最终URL变成了&——这会让服务器完全无法正确识别请求参数,自然返回异常。
正确的做法是直接用&作为URL参数的分隔符,修改后的URL代码:
URL UrlOpenRequest = new URL("http://example.com/docs/modules/content/applet_controller.php?action=editObject&objectType=resource&objectTable=res_version_business&objectId=206");
2. POST请求体的参数分隔符也犯了同样错误
在写入POST表单数据时,你同样用了&来分隔fileContent和fileExtension,这会导致服务器无法解析POST参数。同样替换成普通的&:
writer.write("fileContent=" + this.fileContentTosend + "&fileExtension=" + this.fileExtension);
3. 缺少必要的请求头设置
发送POST表单数据时,必须设置Content-Type请求头为application/x-www-form-urlencoded,否则服务器可能无法识别请求体格式。在打开连接后添加这行代码:
HttpOpenRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
4. 不要依赖available()判断响应数据
HttpURLConnection.getInputStream().available()只能返回当前已读取到内存的字节数,不代表整个响应的总长度,用它来判断是否有数据完全不准确,直接读取输入流即可。
额外提示:参数编码问题
如果fileContentTosend或fileExtension包含特殊字符(比如空格、&、=等),一定要用URLEncoder.encode()进行编码,避免参数解析混乱:
String encodedFileContent = URLEncoder.encode(this.fileContentTosend, "UTF-8"); String encodedFileExtension = URLEncoder.encode(this.fileExtension, "UTF-8"); writer.write("fileContent=" + encodedFileContent + "&fileExtension=" + encodedFileExtension);
完整修复后的代码片段
public void sendHttpRequest(String theUrl, String postRequest) throws Exception { // 修复URL参数分隔符 URL UrlOpenRequest = new URL("http://example.com/docs/modules/content/applet_controller.php?action=editObject&objectType=resource&objectTable=res_version_business&objectId=206"); System.out.println("UrlOpenRequest: " + UrlOpenRequest.toString()); HttpURLConnection HttpOpenRequest = (HttpURLConnection) UrlOpenRequest.openConnection(); HttpOpenRequest.setRequestMethod("POST"); HttpOpenRequest.setRequestProperty("Accept", "*/*"); // 添加必要的Content-Type请求头 HttpOpenRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); HttpOpenRequest.setDoInput(true); HttpOpenRequest.setDoOutput(true); if (!"none".equals(postRequest)) { // 修复POST参数分隔符 + 可选参数编码 String encodedFileContent = URLEncoder.encode(this.fileContentTosend, "UTF-8"); String encodedFileExtension = URLEncoder.encode(this.fileExtension, "UTF-8"); OutputStreamWriter writer = new OutputStreamWriter(HttpOpenRequest.getOutputStream()); writer.write("fileContent=" + encodedFileContent + "&fileExtension=" + encodedFileExtension); writer.flush(); writer.close(); // 记得关闭流释放资源 } else { OutputStreamWriter writer = new OutputStreamWriter(HttpOpenRequest.getOutputStream()); writer.write("foo=bar"); writer.flush(); writer.close(); } // 直接读取输入流解析XML this.parse_xml(HttpOpenRequest.getInputStream()); HttpOpenRequest.disconnect(); }
内容的提问来源于stack exchange,提问作者Imane
相关产品推荐
相关产品推荐

