⑴ java调用URL错误,报505
HttpURLConnection 请求中 参数中如果有 空格,请求则会 505错误
解决: 需要对有空格的参数 做URL编码处理。
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.net.MalformedURLException;
importjava.net.URL;
importjava.net.URLEncoder;
importsun.net.www.protocol.http.HttpURLConnection;
importcom.alibaba.fastjson.JSONObject;
{
="http://localhost:8080/agd-restful/services/restful/QueryService/queryData/*?queryParam=";
publicstaticvoidmain(String[]args)
{
JSONObjectobj=newJSONObject();
obj.put("XM","匡匡");
obj.put("BIRTHDAY",<spanstyle="color:#FF6666;">getURLEncoder</span>("1988-01-0100:00:00,1988-12-3000:00:00"));
Stringurls=targetURL+obj.toString();
requestRestServer(urls);
}
(Stringurl)
{
JSONObjectobj=newJSONObject();
try
{
URLrestServiceURL=newURL(url);
=(HttpURLConnection)restServiceURL.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Accept","application/json");
httpConnection.setRequestProperty("Accept-Charset","UTF-8");
httpConnection.setRequestProperty("contentType","UTF-8");
if(httpConnection.getResponseCode()!=200){
thrownewRuntimeException(":"
+httpConnection.getResponseCode());
}
BufferedReaderresponseBuffer=newBufferedReader(newInputStreamReader(
(httpConnection.getInputStream()),"utf-8"));
Stringoutput="";
Stringresult="";
System.out.println("OutputfromServer: ");
while((output=responseBuffer.readLine())!=null){
//System.out.println(output);
result=output;
}
obj=JSONObject.parseObject(result);
System.out.println(obj.toString());
httpConnection.disconnect();
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
returnobj;
}
@SuppressWarnings("deprecation")
<spanstyle="color:#FF6666;">(Stringdest)
{
returnURLEncoder.encode(dest);
}</span>
}
修改后 正常ok