原因:
出现这个错误的原因是你的url的长度太长了
对于http协议本身,url是没有长度限制的,但是对于浏览器和web服务器来说,鉴于性能等方面的考虑,对url进行了限制
解决方法:
注意:send1方法不能解决这个问题,send2才可以解决,send1加在这里是为了对比效果
public static String send1(String msgUrl) throws IOException {
// String temp = new String(sb.toString().getBytes("GBK"),"UTF-8");
System.out.println("msgUrl:" + msgUrl);
log.info("msgUrl:" + msgUrl);
URL url = new URL(msgUrl);
// 打开url连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置url请求方式 ‘get’ 或者 ‘post’
connection.setRequestMethod("POST");
connection.setConnectTimeout(10000);
// 发送
InputStream is = url.openStream();
// 转换返回值
String returnStr = SenderUtils.convertStreamToString(is);
// 返回结果为‘0,20140009090990,1,提交成功’ 发送成功 具体见说明文档
log.info(returnStr);
// 返回发送结果
return returnStr;
}
public static String send2(String url, String param) throws Exception {
URL localURL = new URL(url);
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(param.length()));
httpURLConnection.setConnectTimeout(10000);
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
String resultBuffer = "";
try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(param.toString());
outputStreamWriter.flush();
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
inputStream = httpURLConnection.getInputStream();
resultBuffer = convertStreamToString(inputStream);
System.out.println(resultBuffer);
} catch (Exception e) {
e.printStackTrace();
log.error("SenderUtils.send message exception:" + e.getMessage());
} finally {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return resultBuffer;
}
public static String convertStreamToString(InputStream is) {
StringBuilder sb1 = new StringBuilder();
byte[] bytes = new byte[4096];
int size = 0;
try {
while ((size = is.read(bytes)) > 0) {
String str = new String(bytes, 0, size, "UTF-8");
sb1.append(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb1.toString();
}