我在Camel中有一个长时间运行的进程,它是由HTTP请求触发的。我想将状态更新写入Outputstream,但在客户端没有得到响应。
我尝试使用以下内容:
骆驼路线:
<from uri="jetty:http://localhost:12345/myservice"/>
<process ref="test" />
处理器测试:
public void process(Exchange arg0) throws Exception {
System.out.println("TestProcessor");
HttpServletResponse response = (HttpServletResponse) arg0.getIn().getHeader(Exchange.HTTP_SERVLET_RESPONSE);
OutputStreamWriter wr = new OutputStreamWriter(response.getOutputStream());
BufferedWriter w = new BufferedWriter(wr);
for(int x = 0; x < 10; x++){
w.write("Zeile: " + x + "n");
w.newLine();
}
// arg0.getIn().setBody("This might also be a response");
}
呼叫代码:
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "GET" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
new Thread(new Runnable(){
@Override
public void run() {
try {
if(!urlParameters.isEmpty()){
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write( postData );
wr.close();
}
}
InputStream s = conn.getInputStream();
System.out.println("got InputStream");
InputStreamReader is = new InputStreamReader(s);
BufferedReader br = new BufferedReader(is);
String line;
while((line = br.readLine()) != null){
System.out.println("ReadLine: " + line);
}
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
但只有当我在处理器中设置主体(注释行)时,我才会得到响应。有什么方法可以保持骆驼的联系并继续写信给它吗?
您应该使用out
消息发送带有HTTP组件的答案:
arg0.getOut().setBody("This might also be a response");
HTTP组件使用HttpBinding
将HttpServletRequest
转换为Exchange
,相反,从Exchange
填充HttpServletResponse
。您可以在这里看到默认实现,也可以提供自己的实现。