需要示例标题和Cookie

时间:2016-05-26 20:22:25

标签: codenameone

IDE:NetBeans 桌面操作系统Windows 10 模拟器Android / iOS 设备Android / iOS

我能够通过身份验证来处理连接请求。我必须得到标题信息,然后在应用程序的另一部分,将相同的信息发送回cgi-bin。下面是我的代码,我评论了我认为我需要用标题和/或cookie做的事情的部分。我对此非常陌生,甚至很难找到基本的标题/ Cookie教程。

/**
 * Your application code goes here<br>
 * This file was generated by <a href="https://www.codenameone.com/">Codename One</a> for the purpose 
 * of building native mobile applications using Java.
 */


package userclasses;

import com.codename1.io.ConnectionRequest;
import com.codename1.io.Cookie;
import com.codename1.io.NetworkEvent;
import com.codename1.io.NetworkManager;
import com.codename1.io.Storage;
import com.codename1.notifications.LocalNotification;
import generated.StateMachineBase;
import com.codename1.ui.*; 
import com.codename1.ui.events.*;
import com.codename1.ui.util.Resources;


import java.util.Timer;
import java.util.TimerTask;
//import org.apache.commons.httpclient.UsernamePasswordCredentials;
//import org.apache.commons.httpclient.auth.AuthScope;

/**
 *
 * @John Barrett
 */
public class StateMachine extends StateMachineBase {
public StateMachine(String resFile) {
    super(resFile);
    // do not modify, write code in initVars and initialize class members there,
    // the constructor might be invoked too late due to race conditions that might occur
}

/**
 * this method should be used to initialize variables instead of
 * the constructor/class scope to avoid race conditions
 */
protected void initVars(Resources res) {
}
boolean stop = false;
boolean notify = false;
String OnOff;


@Override // Starts monitor action.
protected void onMain_ButtonAction(Component c, ActionEvent event){

    // starts a timer to repeat monitor every minute.
    Timer timer = new Timer();
    String text = (String) Storage.getInstance().readObject("SavedData");

    timer.schedule( new TimerTask(){


    @Override
    public void run(){       
    if (stop == true){
        cancel();//Monitor ends           
    } 

    //Starts a connection with the URL to monitor
    ConnectionRequest r = new ConnectionRequest();
    r.setUrl("http://vault.infinitevault.com/cgi-bin/absentmedia?customer=" + text.toLowerCase().trim());
    r.setPost(true);

    // Post Header/Cookie information to URL for access NEED HELP WITH THIS!
    r.setHttpMethod("HEAD");
    r.setContentType("text/xml");
    r.setCookiesEnabled(true);
    findCodeLabel(c).setText("Monitoring: " + text.toUpperCase());
    r.addResponseListener(new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent ev){



                    // Monitor starts 
                    try{

                    NetworkEvent event = (NetworkEvent) ev;
                    // Need to post header/cookie information here? HELP!
                    Cookie.isAutoStored();
                    byte[] data= (byte[]) event.getMetaData();
                    String decodedData = new String(data,"UTF-8");                           

                    boolean none;

                    none = decodedData.endsWith("NONE\n");


                    if (!none){                           



                    System.out.println(decodedData);                            

                        findCodeTextArea(c).setText(decodedData);

                        LocalNotification n = new LocalNotification();
                        n.setId("OSStorage");
                        n.setAlertBody(decodedData);
                        n.setAlertTitle("Absent Media");                

                        Display.getInstance().scheduleLocalNotification(
                                n,
                                System.currentTimeMillis() + 10 * 1000, // fire date/time
                                LocalNotification.REPEAT_MINUTE  // Whether to repeat and what frequency
                        );

                        if (notify != true){
                            Display.getInstance().vibrate(5000);
                        } 
                        Storage.getInstance().writeObject("MonitorData", decodedData);
                    }
                    else{
                System.out.println("None");
                        findCodeTextArea(c).setText("System is Good");
                    }
                    } 
                    catch (Exception ex){
                        ex.printStackTrace();
                    }              

    }

    }); 

    NetworkManager.getInstance().addToQueue(r);       

    }

    }, 0, 60*1000);

}   

@Override // Stops the monitoring action.
protected void onMain_StopButtonAction(Component c, ActionEvent event) {
    super.onMain_StopButtonAction(c, event);//To change body of generated methods, choose Tools | Templates.
    stop = true;

    findCodeLabel(c).setText("Monitor Stopped");
    findCodeTextArea(c).setText("");
    findCodeTextArea(c).setHint("System information will show here");       
    Storage.getInstance().deleteStorageFile("MonitorData");

}


@Override // Saves the settings to storage.
protected void onSettings_SetSaveAction(Component c, ActionEvent event) {

    String Station = findSetStation(c).getText();

    Storage.getInstance().writeObject("SavedData", Station);
    String LoadStation = (String) Storage.getInstance().readObject("SavedData");
    findStationLabel(c).setText("Saved Station is " + LoadStation);


}

@Override // Sets what is saved to appear when in settings.
protected void beforeSettings(Form f) {

    String LoadStation = (String) Storage.getInstance().readObject("SavedData");
    findStationLabel(f).setText("Saved Station is " + LoadStation);
    findSetStation(f).setText(LoadStation);

    String CurrentNotify = (String) Storage.getInstance().readObject("OnOff");
    findSetNotifyLabel(f).setText("Vibration is " + CurrentNotify);
}



@Override // Sets what is saved to appear when in monitor screen.
protected void beforeMain(Form f) {
    String LoadStation = (String) Storage.getInstance().readObject("SavedData");
    findCodeLabel(f).setText(LoadStation);
    if (findCodeTextArea(f) != null){
        String foundData = (String) Storage.getInstance().readObject("MonitorData");
        findCodeTextArea(f).setText(foundData);



    }

}



@Override // Sets notification for turning vibration on.
protected void onSettings_SetNotifyOnAction(Component c, ActionEvent event) {
    notify = false;
    OnOff = "ON";
    Storage.getInstance().writeObject("NotifyOn", notify);
    Storage.getInstance().writeObject("OnOff", OnOff);
    findSetNotifyLabel(c).setText("Vibration is " + OnOff);

}


@Override // Sets notification for turning vibration off.
protected void onSettings_SetNotifyOffAction(Component c, ActionEvent event) {
    notify = true;
    OnOff = "OFF";
    Storage.getInstance().writeObject("NotifyOn", notify);
    Storage.getInstance().writeObject("OnOff", OnOff);
    findSetNotifyLabel(c).setText("Vibration is " + OnOff);

}


@Override // Sets message for monitoring or not.
protected void beforeStartPage(Form f) {
Storage.getInstance().deleteStorageFile("MonitorData");
String LoadStation = (String) Storage.getInstance().readObject("SavedData");


}

@Override // Login button pressed after entering username and password.
protected void onLogin_LoginAction(Component c, ActionEvent event) {

// Gets the username and password entered.
String userName = findUsename().getText();
String passWord = findPassword().getText();

// Establishes a conneciton to authentication.
ConnectionRequest req=new ConnectionRequest();
req.setPost(false);

req.setUrl("http://authentication.infinitevault.com/validate.php");

req.addArgument("username",userName);
req.addArgument("password",passWord);
req.addArgument("grant_type","client_credentials");

// To get the Header/Cookie information.
req.getHttpMethod();
req.setCookiesEnabled(true);

Cookie.setAutoStored(true);
Cookie.isAutoStored();

// Sends message to user that system is verifying.
findDenied(c).setText("Verifying");

NetworkManager.getInstance().addToQueueAndWait(req);

if (req.getResponseData() != null) {
    String token = new String(req.getResponseData());
    token = token.substring(token.indexOf('=') + 1);
    System.out.println(token);

    // Checks credentials if response is denied, goes back, 
    // If response is authenticated goes to main monitor form.
    if (token.endsWith("denied")){


        /*try {
        Thread.sleep(2000);                 //1000 milliseconds is one second.
        } catch(InterruptedException e) {
        Thread.currentThread().interrupt();
        }*/

        back();

    }
    else {
        showForm("Main",null);
    }

}




}









}//end of app

1 个答案:

答案 0 :(得分:0)

只需覆盖连接请求方法cookieReceived(Cookie c)并处理每个cookie的逻辑。