我有一个调用Web服务的数据访问对象。在我的浏览器中,我可以使用网址访问网络服务并且成功。
http://mycompany:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json
但是当我尝试在我的数据访问对象中执行下面的代码时,我收到405错误,说明方法不允许。
String requestURI = "http://mycompany:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json";
URL url = new URL(requestURI);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("GET");
httpCon.setRequestProperty("Accept", "application/json");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
int responseCode = httpCon.getResponseCode();
String responseMessage = httpCon.getResponseMessage();
BufferedReader rd = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
String jsonResponse = sb.toString();
out.close();
httpCon.disconnect();
有人可以帮我解决这里可能出错的问题吗?
也许有更好的方法来执行外部应用程序的Web服务并使用struts读取响应?或者人们认为这种方法没问题?
感谢
答案 0 :(得分:1)
如果你正在使用GET方法。请尝试以下代码。
string url = String.Format("http://somedomain.com/samplerequest?greeting={0}",param);
WebClient serviceRequest = new WebClient();
serviceRequest.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = serviceRequest.DownloadString(new Uri(url));
答案 1 :(得分:0)
感谢你的想法,但不是他们的想法是对的。我使用下面的代码修复了405 ...
String requestURI = "http://myserver:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json";
URL url = new URL(requestURI);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
答案 2 :(得分:-1)
致电httpCon.getOutputStream());
,您不再发送HTTP GET
,而是HTTP POST
。
注意:这是假设您最终获得Sun提供的实施。为了向后兼容,将把GET更改为POST。