2013-08-29 38 views
0

我正在写一个客户端j2me应用程序,它使用post方法连接到基于php的api。出于安全目的,应用程序和api应该在30分钟超时的会话中进行交互。我的问题是,即使会话超时尚未完成,应用程序用户也必须保持登录状态。我的php代码很好,因为我已经在浏览器上测试过了,它工作正常。但是,但应用程序失败,我必须继续登录。我可能会错过什么?这些是使用我的Java应用程序发送到服务器的头文件。成功的php会话需要什么?

String phonenumber = this.phonenumberTextbox.getString(); 
String password = this.passwordTextBox.getString(); 
HttpConnection httpConn = null; 
String url = "http://192.168.56.1/?action=login-user"; 
InputStream is; 
OutputStream os; 
is = null; 
os = null; 
String sReply = ""; 
boolean loggedIn = false; 
try { 
    // Open an HTTP Connection object 
    httpConn = (HttpConnection) Connector.open(url); 
    // Setup HTTP Request to POST 
    httpConn.setRequestMethod(HttpConnection.POST); 
    httpConn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0"); 
    httpConn.setRequestProperty("Accept_Language", "en-US"); 
    //Content-Type is must to pass parameters in POST Request 
    httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
      os = httpConn.openOutputStream(); 
    String params; 
    params = "phonenumber=" + phonenumber + "&password=" + password; 
    os.write(params.getBytes()); 

    // Read Response from the Server 
    StringBuffer sb = new StringBuffer(); 
    is = httpConn.openDataInputStream(); 
    int chr; 
    while ((chr = is.read()) != -1) { 
     sb.append((char) chr); 
    } 
    // Web Server just returns stuff   
    sReply = sb.toString(); 
} catch (IOException ex) { 
    System.out.println("Cannot find server"); 
} finally { 
    if (is != null) { 
     try { 
      is.close(); 
     } catch (IOException ex) { 
     } 
    } 
    if (os != null) { 
     try { 
      os.close(); 
     } catch (IOException ex) { 
     } 
    } 
    if (httpConn != null) { 
     try { 
      httpConn.close(); 
     } catch (IOException ex) { 
     } 
    } 
} 
// do something with sReply 
+1

我认为你错过了Cookies(如果你在php中使用session_start(),你需要PHPSESSID cookie) – Christoph

回答

1

这些天在PHP中的默认实践**在处理会话时如果为PHP生成一个cookie以供客户端存储。您的Java客户端必须存储此cookie(默认情况下称为phpsessid,但任何值得使用的PHP程序员都会更改cookie名称),并将其显示在后续请求的HTTP标头中。

我对Java中的HTTP支持不是很熟悉,但如果它像curl那样,它将包含用于设置和检索cookie的选项。

**在发出请求时,它曾经有可能通过查询字符串(GET参数)传递会话标记,但由于这是非常不安全的并且泄露了潜在的敏感信息,所以它不再使用,甚至可能不会更长的时间作为一个选项。