请java 发送Http请求,后返回的值少了,第一个字符,是什么原因?请各位大虾帮帮忙

//发送代码
public static void main(String[] args) throws Exception{
String urlString="
http://localhost:8080/NewB/callcenter?ac=crmuser
";
URL url = new URL(urlString);
HttpURLConnection url_con= (HttpURLConnection)url.openConnection();
url_con.setDoOutput(true);
url_con.setRequestMethod("GET");
url_con.getOutputStream().flush();
url_con.getOutputStream().close();
InputStream in =url_con.getInputStream();

StringBuilder temp = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
// rd.reset();
while(rd.read()!=-1){
temp.append(rd.readLine());
}
System.out.println(new String (temp));

}
//服务器代码。
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
@SuppressWarnings("unchecked")
Map<String, String> params = request.getParameterMap();
if (params.containsKey("ac")){
PrintWriter write=response.getWriter();
write.println("1-china");
}
}
//当发送请求后,打印的结果是:
-china
这是什么原因?
最新回答
我不勇敢

2024-11-27 15:13:37

// rd.reset();
while(rd.read()!=-1){
temp.append(rd.readLine());
}

问题就出在你的rd.read()上,你调用了一次read(),就会从底层的二进制流中读取一个byte出来,而“1”这个字符不论什么编码,都是只用一个byte表示,所以会丢了一个1。
正确的作法是这样:

String respStr = null;
while ( (respStr = rd.readLine() ) != null ) {
temp.append(respStr);

}