我使用 HttpURLConnection 调用了 Restful Web Service。下面是我的代码摘要:
休息层
@Path("/ResourceName")
@Scope("request")
@SuppressWarnings("unchecked")
public class AlertResource {
@POST
@Path("/methodName")
@Produces({ MediaType.APPLICATION_JSON })
public Response methodName(
@@HeaderParam(value = "xxxx") String param1){
.....
}
动作层
public static String callRestfulApp(String urlString, String methodType,
Map<String, String> parameter) throws Exception{
InputStream inputStream = null;
StringBuilder responseText = new StringBuilder();
HttpURLConnection httpUrlCon = null;
try {
URL url;
StringBuilder urlData = new StringBuilder();
urlData.append(urlString);
url = new URL(urlData.toString());
httpUrlCon = (HttpURLConnection) url.openConnection();
httpUrlCon.setDoOutput(true);
httpUrlCon.setRequestMethod(methodType);
if (parameter != null) {
// Set the parameters
for (Map.Entry<String, String> entry : parameter.entrySet()) {
httpUrlCon.setRequestProperty(entry.getKey(),entry.getValue());
}
}
inputStream = httpUrlCon.getInputStream();
.....
我使用以下行调用了它,
parameters.put("xxxx",
gson.toJson(someBean));
respons = CommonWebUtils.callRestfulApp(prop.getPropertyValue("RestURI") + "ResourceName/methodName",
"POST", parameters);
上面代码的问题是,我的“someBean”包含大量数据,因此;httpUrlCon.getInputStream() 导致 IOException。如果我传递的数据较少,那么它的工作正常。我尝试过使用 dirrerent 参数传递技术(查询,矩阵),但这些都没有帮助我。那么,如何传递大量数据?
异常跟踪:
java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8091/Restful/ResourceName/methodName
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at org.razorsight.alert.web.common.CommonWebUtils.callRestfulApp1(CommonWebUtils.java:149)
at org.razorsight.alert.web.action.KpiAction.addKpiRule(KpiAction.java:245)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)