gpt4 book ai didi

java - 尝试在应用程序和 servlet 之间建立连接时,URLConnection.getInputStream() 抛出 FileNotFoundException

转载 作者:行者123 更新时间:2023-11-28 22:22:04 25 4
gpt4 key购买 nike

我想开发一个在 Tomcat 上运行的 servlet 文件之间进行通信的应用程序。

下面是我的应用程序中的代码,它试图连接到这个 servlet,发送请求并获得响应。

 private URLConnection getServletConnection() {
try {
URL servletURL = new URL("http://localhost:8080/test/servlet");
URLConnection conn = servletURL.openConnection();

conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
return conn;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

下面是抛出异常的代码:

URLConnection conn = getServletConnection();
OutputStream outputStream = conn.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outputStream);
ServletRequestMessage srm = new ServletRequestMessage(2, username, password);
oos.writeObject(srm);
oos.flush();
oos.close();
InputStream inputStream = conn.getInputStream();

异常(exception)情况是:

java.io.FileNotFoundException: http://localhost:8080/test/servlet

谁能帮帮我?谢谢。

最佳答案

服务器端

public class ServletImpl extends HttpServlet implements Servlet {

....
public ServletImpl() {
super();
}

public void init(ServletConfig config) throws ServletException{
super.init(config);


/*
Application scope
Shared between all servlets, JSP pages, and custom tags within a J2EE application
or within the whole container if no applications are defined.
The programmatic interface to the application scope is the 'ServletContext' object.
*/


ServletContext context = config.getServletContext();
context.setAttribute("base", config.getInitParameter("base"));
/* where "base" is iniy param in web.xml
<init-param>
<param-name>base</param-name>
<param-value>/ServlrtName/sys</param-value>
</init-param>


*/



....



}
....
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}


protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
Enumeration<?> paramNames = request.getParameterNames();


while(paramNames.hasMoreElements()) {

String paramName = (String)paramNames.nextElement();

String[] paramValues = request.getParameterValues(paramName);


if("sub".equals(paramName)){

paramValues = request.getParameterValues(paramName);

if(paramValues.length > 0){

String param = paramValues[0];
// do something
....
}

}
}
}


....
// prepear response
response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println(mMessageResponseStr);
out.close();

这里我使用了 sub 标签,参见:if("sub".equals(paramName)){.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ServlrtName</display-name>
<servlet>
<description>
</description>
<display-name>ServlrtName</display-name>
<servlet-name>ServlrtName</servlet-name>
<servlet-class>com.demo.servlet.ServletImpl</servlet-class>
<init-param>
<param-name>base</param-name>
<param-value>/ServlrtName/sys</param-value>
</init-param>
<init-param>

....

</servlet>

...

<servlet-mapping>
<servlet-name>ServlrtName</servlet-name>
<url-pattern>/sys/*</url-pattern>
</servlet-mapping>

客户端

我使用了 DefaultHttpClientHttpPost。我发送 sub 标签。下面是一个向 Servlet 发送数据的方法:

 public boolean send(String data) {

DefaultHttpClient httpclient = null;
boolean success = false;

try {
httpclient = new DefaultHttpClient();

String url = "your URL";


HttpPost httpost = new HttpPost(url);

List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("sub", data));


httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));


HttpResponse response = httpclient.execute(httpost);

HttpEntity entity = response.getEntity();

if (entity != null) {

StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();

if(statusCode != 200){
mResErr.onErrorResponse(statusCode);
}

InputStream is = entity.getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ( (line = br.readLine()) != null) {

// get data from line


}
is.close();


} else {
//response is null/
}
success = true;

mRes.onHttpResponse(mArr);


} catch (Exception e) {
mResErr.onErrorResponse(e);
e.getStackTrace();
}

if (httpclient != null) {
// resource cleanup
httpclient.getConnectionManager().shutdown();
}

return success;
}

** 评论,在开始检查连接之前,从服务器端删除用户/密码。如果一切按预期工作,将其切换回来并在客户端使用:

Credentials cred = new UsernamePasswordCredentials("user", "pswd");


httpclient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
cred);

关于java - 尝试在应用程序和 servlet 之间建立连接时,URLConnection.getInputStream() 抛出 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12995916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com