Передать строку из Java в веб-приложение Java EE и вернуть обратно строку - PullRequest
0 голосов
/ 06 марта 2012

Я пытаюсь создать приложение для Android / Java, которое должно подключаться к веб-сервису Java EE, которое я сделаю. Мне нужно, чтобы он передавал строку, вызывал действие и сканировал базу данных на основе этой строки и возвращал другую строку обратно в приложение java / android.

Пока у меня есть возможность отправить строку на страницу JSP, и она возвращает строку. Мне просто нужно знать, как направить строку в действие, чтобы я мог выполнять запросы к БД и тому подобное в своем веб-приложении. Ниже то, что я имею до сих пор.

JSP

java.util.Enumeration e = request.getParameterNames();
while (e.hasMoreElements())
{
String pName = (String)e.nextElement();
String pValue = request.getParameter(pName);
String theURL = "index.do"+ "?Parameter1=" + pValue;

//theURL = response.encodeRedirectURL(theURL);

//response.sendRedirect(theURL);
%>

Value :<%=theURL%><%
break;
}

Java класс импорт java.net. ; import java.util. ; импорт java.io. *;

/ ** * Пример метода POST в HTTP.
* / общедоступный класс {

 public static void main (String[] args) throws Exception 
 { 
    // Populate the hashtable with key value pairs of 
    // the parameter name and 
    // value. In this case, we only have the parameter 
    // named "CONTENT" and the 
    // value of CONTENT will be "HELLO JSP !" 

    Hashtable h = new Hashtable(); 
    h.put("CONTENT", "I like stuff"); 
    h.put("ONEMORECONTENT", "HELLO POST !"); 

    // POST it ! 
    String output = POST("xxxxxxxxxxx.jsp", 
                         h); 

    System.out.println(output); 
 } 

/** 
 * The POST method. Accepts 2 parameters 
 * @param targetURL : The URL to POST to. 
 * @param contentHash : The hashtable of the paramters to be posted. 
 *  
 * @return The String returned as a result of POSTing. 
 */ 
public static String POST(String targetURL, Hashtable contentHash) throws Exception 
{     
    URL url; 
    URLConnection conn; 

    // The data streams used to read from and write to the URL connection. 
    DataOutputStream out; 
    DataInputStream in; 

    // String returned as the result of the POST. 
    String returnString = ""; 

    // Create the URL object and make a connection to it. 
    url = new URL (targetURL); 
    conn = url.openConnection(); 

    // Set connection parameters. We need to perform input and output, 
    // so set both as true. 
    conn.setDoInput (true); 
    conn.setDoOutput (true); 

    // Disable use of caches. 
    conn.setUseCaches (false); 

    // Set the content type we are POSTing. We impersonate it as 
    // encoded form data 
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

    // get the output stream to POST to. 
    out = new DataOutputStream (conn.getOutputStream ()); 
    String content = ""; 

    // Create a single String value to be POSTED from the parameters passed 
    // to us. This is done by making "name"="value" pairs for all the keys 
    // in the Hashtable passed to us. 
    Enumeration e = contentHash.keys(); 
    boolean first = true; 
    while(e.hasMoreElements()) 
    {             
        // For each key and value pair in the hashtable 
        Object key = e.nextElement(); 
        Object value = contentHash.get(key); 

        // If this is not the first key-value pair in the hashtable, 
        // concantenate an "&" sign to the constructed String 
        if(!first)  
            content += "&"; 

        // append to a single string. Encode the value portion 
        content += (String)key + "=" + URLEncoder.encode((String)value); 

        first = false; 
    } 

    // Write out the bytes of the content string to the stream. 
    out.writeBytes (content); 
    out.flush (); 
    out.close (); 

    // Read input from the input stream. 
    in = new DataInputStream (conn.getInputStream ()); 

    String str;         
    while (null != ((str = in.readLine()))) 
    { 
        returnString += str + "\n"; 
    } 

    in.close (); 

    // return the string that was read. 
    return returnString; 
} 

}

Выход: Значение: index.do? Parameter1 = мне нравится материал

Заранее спасибо!

1 Ответ

0 голосов
/ 07 марта 2012

Самый простой способ решить вашу проблему - внедрить HttpServlet. Вы можете использовать клиент из вашего примера. Вы должны реализовать метод doPost (запрос, ответ).

Вы можете просто получить доступ к параметрам, вызвав

for (String parameterName : request.getParameters()) {
  String value = request.getParameter(parameterName);
  // store parameter values in any structure you need
  ...
}
// here you cann access any class from your web application to perform
// DB operations.
...
// to propagate result to client obtain an OutputStream from response object
// and simply write data to it
OutputStream os = response.getOutputStream();
os.write(your data);

Другой способ работы персонала - использование стандартных веб-сервисов. Я не знаю программирования на Android, но эта ссылка, кажется, показывает хороший пример: http://www.ibm.com/developerworks/webservices/library/ws-android/index.html?ca=drs-

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...