I made a JSP that is supposed to upload a file into a directory and it shows me an error when trying to connect:
Here you can see my codes:
If anyone can help me i would appriciate it.
package src;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
public class Controller extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
String saveFile="c:\\uploaddir\\";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String actiune="afiseaza";
PrintWriter out=response.getWriter();
if (request.getParameter("actiune")!=null)
{
actiune = request.getParameter("actiune");
}
if (actiune.equals("afiseaza"))
{
doAfiseaza(request, response);
}
if (actiune.equals("sterge"))
{
doDeleteFile(request, response);
}
try{
boolean ismultipart=ServletFileUpload.isMultipartContent(request);
if(!ismultipart)
{
}
else
{
FileItemFactory factory= new DiskFileItemFactory();
ServletFileUpload upload= new ServletFileUpload(factory);
List items=null;
try{
items=upload.parseRequest(request);
}catch(Exception e)
{
}
Iterator itr=items.iterator();
while(itr.hasNext())
{
FileItem item= (FileItem)itr.next();
if(item.isFormField())
{
}
else
{
String itemname=item.getName();
if((itemname==null)||itemname.equals(""))
{
continue;
}
String filename=FilenameUtils.getName(itemname);
File f=checkExist(filename);
item.write(f);
}
}
}
}catch(Exception e)
{
}
finally{
out.close();
}
}
private void doDeleteFile(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String fName=URLDecoder.decode(request.getParameter("fis"));
File f = new File("c:\\uploaddir\\"+fName);
f.delete();
doAfiseaza(request, response);
}
private void doAfiseaza(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String dir = "c:\\uploaddir";
int er = 0;
File[] lista = null;
try
{
File f = new File(dir);
lista = f.listFiles();
}
catch(Exception ex)
{
er=-1;
}
request.setAttribute("eroare", new Integer(er));
request.setAttribute("lista", lista);
RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/lista.jsp");
rd.forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Prima aplicatie";
}// </editor-fold>
private File checkExist(String fileName) {
File f=new File(saveFile+"/"+fileName);
if(f.exists())
{
StringBuffer sb=new StringBuffer(fileName);
sb.insert(sb.lastIndexOf("."), "-"+new Date().getTime());
f=new File(saveFile+"/"+sb.toString());
}
return f;
}
}
so now i have no errors but it doesnt upload my folder so i dont know what to do.
Since your original question was about JSP, here is some demonstration code.
<%# page import="java.util.*,
java.io.*,
org.apache.commons.fileupload.*,
org.apache.commons.fileupload.servlet.*,
org.apache.commons.fileupload.disk.*,
org.apache.commons.fileupload.util.*"%>
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
out.print("Request content length is " + request.getContentLength() + "<br/>");
if(isMultipart){
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
FileItemStream item = null;
String name = "";
InputStream stream = null;
while (iter.hasNext()){
item = iter.next();
name = item.getFieldName();
stream = item.openStream();
if(item.isFormField()){out.println("Form field " + name + " with value "
+ Streams.asString(stream) + "<br/>");}
else {
name = item.getName();
if(name != null && !"".equals(name)){
String fileName = new File(item.getName()).getName();
out.println("Client file " + item.getName() + " <br/>with file name "
+ fileName + " uploaded.<br/>");
File file = new File("C:/uploaddir/" + fileName);
FileOutputStream fos = new FileOutputStream(file);
long fileSize = Streams.copy(stream, fos, true);
out.print(fileName
+ " was uploaded to the fileUploads folder. Size was " +
fileSize + "<br/>");
}
}
}
} else out.print("Wrong request type!");
%>
call that JSP with
<html><body>
<form enctype="multipart/form-data" action="fileUpload3.jsp" method="post">
<input type='file' name='file1'/><br/>
<input type='file' name='file2'/><br/>
<input type='file' name='file3'/><br/>
Type message:<input type="text" name="message" /><br/>
<input Type='submit' value='Submit'/>
</form>
</body></html>
Put both files in your web app's root folder.
Related
The way that the program is supposed to work is that there is a javaDB in the background that the servlet can pull from. The servlet gets a keyword from index.jsp and uses that to search the DB to get the information related to that keyword. But the doGet method is not even attempting to run anything in a try/catch block. I know the doGet method is running because I have tried loading test code in there and it does display it, just will not run through the try/catch.
DBConnector.java
package edu.uwf.cs.dsa;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author Bernd
*/
public class DBConnector extends HttpServlet {
private Context env;
#Override
public void init(ServletConfig config)
throws ServletException {
super.init(config);
try {
env = (Context) new InitialContext().lookup("java:comp/env");
} catch (NamingException e) {
throw new ServletException(e.getMessage());
}
}
private String getUrl() throws NamingException
{
return (String)env.lookup("jdbc:derby://localhost:1527/JA112");
}
private Connection getConnection()
throws NamingException, ServletException, ClassNotFoundException, SQLException
{
Class.forName((String)env.lookup("org.apache.derby.jdbc.EmbeddedDriver"));
return DriverManager.getConnection(getUrl());
}
private void getMovies(Connection conn, PrintWriter out) throws SQLException
{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from Student");
while (rs.next()) {
out.print(rs.getString(1)); out.println("<br />");
out.print(" " + rs.getString(2)); out.println("<br />");
out.print(" " + rs.getString(3)); out.println("<br />");
out.print(" " + rs.getString(4)); out.println("<br />");
out.println(" " + rs.getString(5)); out.println("<br />");
}
}
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, NamingException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection conn = getConnection();
// out.print("<html>\n <head>\n <body>\n<h1>test</h1>\n</body>\n</head>\n</html>");
try {
/* TODO output your page here. You may use following sample code. */
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet DBConnector</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet DBConnector at " + request.getContextPath() + "</h1>");
out.println((String)env.lookup("driver"));
out.println("<br />");
out.println(getUrl());
out.println("<br />");
out.println(conn);
getMovies(conn,out);
out.println("<br />");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (Exception e) {
Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, e);
}
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (NamingException ex) {
Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
index.jsp
<%--
Document : index
Created on : Nov 21, 2012, 9:20:16 PM
Author : Bernd
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form method="GET" action="/DBServlet/DBConnector">
<h1>Movie Search</h1>
Enter Keyword <input type="text" name="keyword" id="keyword">
<input type="submit" value="submit" id="button">
</form>
</body>
</html>
My best guess is that the env variable it's been initialized to null in normal testing, you need to add the catch block on the processRequest() method so it will became clear this is the error, for now you only have the finally block, so the Exception it's hidden and unclear.
Once you add the block and see the exception, you'll need to check your config file where you defined the java:comp/env , maybe a typo or something like that could be causing the real problem.
I'm running a page trying to export an Excel file through a Java Servlet. A rundown of the structure:
downloadreports.jsp is where the button is that is supposed to call the file. The button calls ReportsServlet.java, which is just the download and that in turn calls ExcelCreatorBanned.java, which calls the database and creates the Excel file.
The problem is that 1) when I try to click on downloadreports.jsp when running the full site, it automatically goes to the ReportsServlet instead of displaying the page (turning up a 404 error for /Reports) and 2) I've been messing with this for days and it's just not working. Not sure what I'm doing wrong, but any help would be very appreciated!
downloadreports.jsp
<div align="center">
<form id="downloadBanned" action="../Reports" method="post">`
<input class="btn btn-lg btn-red" type="submit" value="Download Banned Student List"><br> `
</form>`
ReportsServlet.java
package controllers;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import helpers.ExcelCreatorBanned;
/**
* Servlet implementation class ReportsServlet
*/
#WebServlet({ "/ReportsServlet", "/Reports" })
public class ReportsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private HttpSession session;
private String url;
/**
* #see HttpServlet#HttpServlet()
*/
public ReportsServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.session = request.getSession(false);
ExcelCreatorBanned ecb = new ExcelCreatorBanned();
ecb.downloadExcel();
url = "admin/downloadreports.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
private Object getOutputStream() {
// TODO Auto-generated method stub
return null;
}
}
ExcelCreatorBanned.java (The reference to DbConnect.java is the credentials to the server, and it definitely works because it works on the other pages)
package helpers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletOutputStream;
import model.DbConnect;
import java.sql.Statement;
public class ExcelCreatorBanned {
public String downloadExcel( ) { //ServletOutputStream out){
String outFileName = "BannedStudents.csv";
int nRow = 1;
String strQuery = null;
Connection con = null;
try {
// Getting connection here for mySQL database
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DbConnect.devCredentials();
System.out.println(con);
if(con==null)
return "Connection Failed";
// Database Query
strQuery = "select * from banned";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(strQuery);
File file = new File(outFileName);
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
//Get Titles
String titleLine = "BannedID" + "," + "UserID" + "," + "AdminID"
+ "," + "Ban Start Date" + "," +
"Ban End Date" + "," + "Penalty Count" + "," +
"Description" + "," + "Status" + "\n";
out.write(titleLine);
//stmt = conn.createStatement();
while (rs.next()) {
int BannedId = rs.getInt(1);
int UserID = rs.getInt(2);
int AdminID = rs.getInt(3);
String BanStartDate = rs.getString(4);
String BanEndDate = rs.getString(5);
int PenaltyCount = rs.getInt(6);
String Description = rs.getString(7);
String Status = rs.getString(8);
String outline = BannedId + "," + UserID + "," + AdminID +
"," + BanStartDate + "," +
BanEndDate + "," + PenaltyCount + "," + Description +
"," + Status + "\n";
out.write(outline);
} //end of while
out.close();
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return outFileName;
}
}
I don't like the look of the action="../Reports" attribute in the line
<form id="downloadBanned" action="../Reports" method="post">
Try the following instead:
<form id="downloadBanned" action="${pageContext.request.contextPath}/Reports" method="post">
See this question for a discussion about what ${pageContext.request.contextPath} is.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author hp
*/
#WebServlet(name = "Getdetails", urlPatterns = {"/Getdetails"})
public class Getdetails extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
Connection con = null;
PreparedStatement ps = null;
Statement st = null;
ResultSet rs = null;
String debitcard = new String();
String debitcardno = new String();
String accountno = new String();
String account = new String();
String cvv = new String();
String pin = new String();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bussinesssolutions?zeroDateTimeBehavior=convertToNull", "root", "root");
ps = con.prepareStatement("select card.debitcardno, card.accountnno, card.cvv, card.pin from card inner join regsiter on card.edebitcardno = regsiter.debitcardno");
ps.setString(1, debitcard);
ps.setString(2, account);
ps.setString(3, cvv);
ps.setString(4, pin);
rs = ps.executeQuery();
debitcardno = rs.getString("debitcardno");
accountno = rs.getString("accountno");
cvv = rs.getString("cvv");
pin = rs.getString("pin");
request.getSession().setAttribute("debitcardno", debitcardno);
request.getSession().setAttribute("accountno", accountno);
request.getSession().setAttribute("cvv", cvv);
request.getSession().setAttribute("pin", pin);
RequestDispatcher rd = request.getRequestDispatcher("Getdetails");
rd.forward(request, response);
} catch (ClassNotFoundException | SQLException | ServletException | IOException e) {
out.print(e);
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(Bankdetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
ps.close();
st.close();
} catch (SQLException ex) {
Logger.getLogger(Bankdetails.class.getName()).log(Level.SEVERE, null, ex);
}
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(Bankdetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
`return` "Short description";
}// </editor-fold>
}
I am getting the above mentioned exception. Don't know why.why such exception is occurring and how to resolve it. I want to fetch the details from the database of the above details but maybe some mistake in code that it is not happening
ps = con.prepareStatement("select card.debitcardno, card.accountnno, card.cvv, " +
"card.pin from card inner join regsiter on card.edebitcardno = regsiter.debitcardno");
There's no ? parameters in this statement. None of the following would work.
ps.setString(1, debitcard);
ps.setString(2, account);
ps.setString(3, cvv);
ps.setString(4, pin);
You need to actually provide parameters to assign.
ps = con.prepareStatement("select card.debitcardno, card.accountnno, card.cvv, " +
"card.pin from card inner join regsiter on " +
"card.edebitcardno = regsiter.debitcardno " +
"where card.debitcardno=? AND card.accountno=? AND card.cvv=? AND card.pin=?");
I'm trying to build a simple gateway in Tomcat, which would do authorization checks and redirect the request to different endpoint, which gets the response and sends it back to the browser.
In Tomcat I have have a simple Servlet, which uses HttpURLConnection to connect to the endpoint, which gets the response and send it back to browser.
However in Chrome my URL always gets redirected to the endpoint domain. I don't see this behavior in IE or Firefox.
For example, this is deployed to hostname test.gateway.com.
If I make a http request test.gateway.com:9500/test/index.html from browser, Servlet should make a http request to test.endpoint.com/test/index.html and return the response. Client browser should remain on test.gateway.com:9500/test/index.html
However on Chrome my URL changes to http://test.endpoint.com/test/index.html
In my web.xml I have URL Mapping which calls this servlet.
Here is the Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class AppProxyServlet
*/
#WebServlet("/AppProxyServlet")
public class AppProxyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String proxy = "http://test.endpoint.com";
/**
* #see HttpServlet#HttpServlet()
*/
public AppProxyServlet() {
super();
// TODO Auto-generated constructor stub
}
private String callEndpoint(HttpServletRequest request, String plexURL)
throws Exception {
// make
String queryString = request.getQueryString();
if (queryString != null && queryString.length() > 0) {
plexURL += "?" + queryString;
}
URL obj = new URL(plexURL);
Cookie[] cookies = request.getCookies();
StringBuffer allCookies = new StringBuffer();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
// if( cookies[ i ].getName() == "SSO")
{
allCookies.append(cookies[i].getName());
allCookies.append("=");
if ("SSO".equals(cookies[i].getName())) {
String ssostr = cookies[i].getValue();
allCookies.append(ssostr);
} else {
allCookies.append(cookies[i].getValue());
}
if (i < cookies.length)
allCookies.append(";");
// con.setRequestProperty("Cookie", cookies[ i
// ].getName()+"="+cookies[i].getValue());
}
}
}
System.out.println("All Cookies:" + allCookies.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setInstanceFollowRedirects(false);
con.setRequestProperty("Accept-Charset", "ISO-8859-1");
con.setRequestProperty("Cookie", allCookies.toString());
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending Get request to URL:" + plexURL);
System.out.println("Response code:" + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream(), "ISO-8859-1")); // iso-8859-1
int value;
StringBuffer response = new StringBuffer();
while ((value = in.read()) != -1) {
char c = (char) value;
response.append(c);
}
con.disconnect();
return (response.toString());
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// ServletContext sc = getServletContext();
StringBuilder URL = new StringBuilder("");
String URI = request.getRequestURI();
System.out.println("Full URL:" + URI);
// Form the URL
URL.append(proxy);
URL.append(URI);
String sspResponse = "";
if (URI.endsWith("css")) {
response.setContentType("text/css");
} else {
response.setContentType("text/html;charset=ISO-8859-1");
}
PrintWriter printWriter = response.getWriter();
try {
sspResponse = callEndPoint(request, URL.toString());
} catch (Exception e) {
System.out.println(e.getStackTrace());
System.out.println("Some exception occured...");
}
printWriter.println(sspResponse);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
I'm trying to get the output from a servlet on an Android phone.
This is my servlet:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package main;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author Bert Verhelst <verhelst_bert#hotmail.com>
*/
public class servlet1 extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet servlet1</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>processing...</h1>");
out.println("</body>");
out.println("</html>");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ "<head><title>Hello WWW</title></head>\n"
+ "<body>\n"
+ "<h1>doget...</h1>\n"
+ "</body></html>");
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ "<head><title>Hello WWW</title></head>\n"
+ "<body>\n"
+ "<h1>dopost...</h1>\n"
+ "</body></html>");
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
This is my Android main page:
package be.smarttelecom.MyTest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView output = (TextView) findViewById(R.id.output);
try {
output.append("starting\n");
RestClient client = new RestClient("http://10.0.0.188:8084/Servlet_1/servlet1");
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
output.append("after execute\n");
String response = client.getResponse();
output.append("class - " + response + "\n" );
output.append(response);
output.append("done\n");
}
catch (Exception ex) {
output.append("error: " + ex.getMessage() + "\n" + ex.toString() + "\n");
}
}
}
And finally we have the RestClient:
package be.smarttelecom.MyTest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
public class RestClient {
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public RestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws Exception
{
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "?";
for(NameValuePair p : params)
{
String paramString = p.getName() + "=" + p.getValue();
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
}
catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Unfortunately this doesn't work. Here is what I get for output (null),
What am I doing wrong?
I request the DoGet method of my servlet and convert the output to a string, but it appears to be empty.
I allowed the Internet connection in the manifest file just after the closing bracket of application,
<uses-permission android:name="android.permission.INTERNET" />
Romain Hippeau wrote in a comment:
Does the call ever get to the servlet? What does the server see is being sent? What is the server sending back?
That was the problem! I disabled my firewall and now it works :)