Java Code Examples for com.codename1.io.ConnectionRequest#setPost()

The following examples show how to use com.codename1.io.ConnectionRequest#setPost() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ServerAccess.java    From codenameone-demos with GNU General Public License v2.0 7 votes vote down vote up
public static List getEntriesFromFlickrService(String tag) {
    
    try {
        ConnectionRequest req = new ConnectionRequest();
        req.setUrl("http://api.flickr.com/services/feeds/photos_public.gne");
        req.setPost(false);
        req.addArgument("tagmode", "any");
        req.addArgument("tags", tag);
        req.addArgument("format", "json");
        
        NetworkManager.getInstance().addToQueueAndWait(req);
        byte[] data = req.getResponseData();
        if (data == null) {
            throw new IOException("Network Err");
        }
        JSONParser parser = new JSONParser();
        Map response = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
        System.out.println("res" + response);
        List items = (List)response.get("items");
        return items;
    } catch (Exception e) {
    }
    return null;
}
 
Example 2
Source File: TwitterRESTService.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Logs in to twitter as an application
 * 
 * @param consumerKey the key to login with
 * @param consumerSecret the secret to to login with
 * @return the authorization token
 */
public static String initToken(String consumerKey, String consumerSecret) {
    ConnectionRequest auth = new ConnectionRequest() {
        protected void readResponse(InputStream input) throws IOException  {
            JSONParser p = new JSONParser();
            Hashtable h = p.parse(new InputStreamReader(input));
            authToken = (String)h.get("access_token");
            if(authToken == null) {
                return;
            }
        }
    };
    auth.setPost(true);
    auth.setUrl("https://api.twitter.com/oauth2/token");
    
    // YOU MUST CHANGE THIS IF YOU BUILD YOUR OWN APP
    String encoded = Base64.encodeNoNewline((consumerKey + ":" + consumerSecret).getBytes());
    auth.addRequestHeader("Authorization", "Basic " + encoded);
    auth.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
    auth.addArgument("grant_type", "client_credentials");
    NetworkManager.getInstance().addToQueueAndWait(auth);
    return authToken;
}
 
Example 3
Source File: AnalyticsService.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private static ConnectionRequest GetGARequest() {
    ConnectionRequest req = new ConnectionRequest();
    req.setUrl("https://www.google-analytics.com/collect");
    req.setPost(true);
    req.setFailSilently(true);
    req.addArgument("v", "1");
    req.addArgument("tid", instance.agent);
    if (timeout > 0) {
        req.setTimeout(timeout);
    }
    if (readTimeout > 0) {
        req.setReadTimeout(readTimeout);
    }
    long uniqueId = Log.getUniqueDeviceId();
    req.addArgument("cid", String.valueOf(uniqueId));
    return req;
}
 
Example 4
Source File: SignIn.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private void showFacebookUser(String token){
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/v2.3/me");
    req.addArgumentNoEncoding("access_token", token);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog d = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(req);
    byte[] data = req.getResponseData();
    JSONParser parser = new JSONParser();
    Map map = null;
    try {
        map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String name = (String) map.get("name");
    d.dispose();
    Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), "https://graph.facebook.com/v2.3/me/picture?access_token=" + token);
    userForm.show();
}
 
Example 5
Source File: AutocompleteOverrideFilterSample.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
String[] searchLocations(String text) {        
    try {
        if(text.length() > 0) {
            if (currRequest != null) {
                //currRequest.kill();
                
            }
                
            ConnectionRequest r = new ConnectionRequest();
            currRequest = r;
            r.setPost(false);
            r.setUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json");
            r.addArgument("key", apiKey.getText());
            r.addArgument("input", text);
            NetworkManager.getInstance().addToQueueAndWait(r);
            Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
            String[] res = Result.fromContent(result).getAsStringArray("//description");
            return res;
        }
    } catch(Exception err) {
        Log.e(err);
    }
    return null;
}
 
Example 6
Source File: FacebookConnect.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected boolean validateToken(String token) {
    //make a call to the API if the return value is 40X the token is not 
    //valid anymore
    final boolean[] retval = new boolean[1];
    retval[0] = true;
    ConnectionRequest req = new ConnectionRequest() {
        @Override
        protected void handleErrorResponseCode(int code, String message) {
            //access token not valid anymore
            if (code >= 400 && code <= 410) {
                retval[0] = false;
                return;
            }
            super.handleErrorResponseCode(code, message);
        }

    };
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/v2.4/me");
    req.addArgumentNoEncoding("access_token", token);
    NetworkManager.getInstance().addToQueueAndWait(req);
    return retval[0];
}
 
Example 7
Source File: GoogleConnect.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected boolean validateToken(String token) {
    //make a call to the API if the return value is 40X the token is not 
    //valid anymore
    final boolean[] retval = new boolean[1];
    retval[0] = true;
    ConnectionRequest req = new ConnectionRequest() {
        @Override
        protected void handleErrorResponseCode(int code, String message) {
            //access token not valid anymore
            if (code >= 400 && code <= 410) {
                retval[0] = false;
                return;
            }
            super.handleErrorResponseCode(code, message);
        }

    };
    req.setPost(false);
    req.setUrl("https://www.googleapis.com/plus/v1/people/me");
    req.addRequestHeader("Authorization", "Bearer " + token);
    NetworkManager.getInstance().addToQueueAndWait(req);
    return retval[0];

}
 
Example 8
Source File: SignIn.java    From codenameone-demos with GNU General Public License v2.0 6 votes vote down vote up
private void showGoogleUser(String token){
    ConnectionRequest req = new ConnectionRequest();
    req.addRequestHeader("Authorization", "Bearer " + token);
    req.setUrl("https://www.googleapis.com/plus/v1/people/me");
    req.setPost(false);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog d = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(req);
    d.dispose();
    byte[] data = req.getResponseData();
    JSONParser parser = new JSONParser();
    Map map = null;
    try {
        map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String name = (String) map.get("displayName");
    Map im = (Map) map.get("image");
    String url = (String) im.get("url");
    Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), url);
    userForm.show();
}
 
Example 9
Source File: SignIn.java    From codenameone-demos with GNU General Public License v2.0 6 votes vote down vote up
private void showFacebookUser(String token){
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/v2.3/me");
    req.addArgumentNoEncoding("access_token", token);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog d = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(req);
    byte[] data = req.getResponseData();
    JSONParser parser = new JSONParser();
    Map map = null;
    try {
        map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String name = (String) map.get("name");
    d.dispose();
    Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), "https://graph.facebook.com/v2.3/me/picture?access_token=" + token);
    userForm.show();
}
 
Example 10
Source File: CloudStorage.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Deletes all the cloud files under this user, notice that this method
 * is asynchronous and a background server process performs the actual deletion
 * @deprecated this API is currently deprecated due to Googles cloud storage deprection
 */
public void deleteAllCloudFilesForUser() {
    if(CloudPersona.getCurrentPersona().getToken() == null) {
        return;
    }
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setFailSilently(true);
    req.setUrl(SERVER_URL + "/purgeCloudFiles");
    req.addArgument("own", CloudPersona.getCurrentPersona().getToken());
    req.addArgument("u", Display.getInstance().getProperty("built_by_user", ""));
    NetworkManager.getInstance().addToQueue(req);
}
 
Example 11
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Some simple queries for public data can work just fine with anonymous login without requiring the whole
 * OAuth process, they still need a facebook application though
 * @param appid the id of the application
 * @param clientSecret the client secret for the application
 */
public static void anonymousLogin(String appid, String clientSecret) {
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/oauth/access_token");
    req.addArgument("client_id", appid);
    req.addArgument("client_secret", clientSecret);
    req.addArgument("grant_type", "client_credentials");
    NetworkManager.getInstance().addToQueueAndWait(req);
    if(req.getResponseData() != null) {
        token = new String(req.getResponseData());
        token = token.substring(token.indexOf('=') + 1);
    }
}
 
Example 12
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * log out the current user
 */
public static void logOut(){
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl("https://www.facebook.com/logout.php?access_token="+token+"&confirm=1&next="+redirectURI);
    NetworkManager.getInstance().addToQueueAndWait(req);
    token = null;
}
 
Example 13
Source File: ParseGetCommand.java    From parse4cn1 with Apache License 2.0 5 votes vote down vote up
@Override
void setUpRequest(ConnectionRequest request) throws ParseException {
    setupDefaultHeaders();
    request.setPost(false);
    request.setHttpMethod("GET");
    request.setUrl(getUrl(endPoint, objectId));
}
 
Example 14
Source File: StateMachine.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void onMain_ImportJSONAction(final Component c, ActionEvent event) {
    ConnectionRequest cr = new ConnectionRequest() {
        protected void readResponse(InputStream is) throws IOException {
            JSONParser p = new JSONParser();
            Hashtable h = p.parse(new InputStreamReader(is));
            Hashtable<Object, Hashtable<String, String>> todoHash = (Hashtable<Object, Hashtable<String, String>>)h.get("todo");
            Container tasksContainer = findTasksContainer(c.getParent());
            for(Hashtable<String, String> values : todoHash.values()) {
                String photoURL = values.get("photoURL");
                String title = values.get("title");

                MultiButton mb = createEntry(values);
                todos.add(values);
                tasksContainer.addComponent(mb);


                if(photoURL != null) {
                    ImageDownloadService.createImageToStorage(photoURL, mb.getIconComponent(), 
                            title, new Dimension(imageWidth, imageHeight));
                }
            }
            Storage.getInstance().writeObject("todos", todos);        
            findTabs1(c.getParent()).setSelectedIndex(0);
            tasksContainer.animateLayout(500);
        }
    };
    InfiniteProgress i = new InfiniteProgress();
    Dialog blocking = i.showInifiniteBlocking();
    cr.setDisposeOnCompletion(blocking);
    cr.setPost(false);
    cr.setUrl("https://dl.dropbox.com/u/57067724/cn1/Course%20Material/webservice/NetworkingChapter.json");
    NetworkManager.getInstance().addToQueue(cr);
}
 
Example 15
Source File: MapsDemo.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
private String getDirections(Coord origin, Coord destination) throws IOException {
    ConnectionRequest req = new ConnectionRequest();
    req.setUrl("http://maps.googleapis.com/maps/api/directions/json");
    req.setUserAgent("Opera/8.0 (Windows NT 5.1; U; en)");
    req.setPost(false);
    req.addArgument("origin", "" + origin.getLatitude() + " " + origin.getLongitude());
    req.addArgument("destination", "" + destination.getLatitude() + " " + destination.getLongitude());
    req.addArgument("mode", "walking");
    req.addArgument("sensor", "false");
    NetworkManager.getInstance().addToQueueAndWait(req);
    JSONParser p = new JSONParser();
    Hashtable h = p.parse(new InputStreamReader(new ByteArrayInputStream(req.getResponseData())));
    System.out.println(h.toString());
    return ((Hashtable) ((Hashtable) ((Vector) h.get("routes")).firstElement()).get("overview_polyline")).get("points").toString();
}
 
Example 16
Source File: CloudImageProperty.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Object propertyValue(CloudObject obj, String propertyName) {
    final String key = (String)obj.getObject(idProperty);
    if(key == null) {
        return placeholderImage;
    }
    Image image = (Image)getCache().get(key);
    if(image == null) {
        ReplaceableImage r = inProgress.get(key);
        if(r != null) {
            return r;
        }
        final ReplaceableImage rp = ReplaceableImage.create(placeholderImage);
        inProgress.put(key, rp);
        ConnectionRequest cr = new ConnectionRequest() {
            private EncodedImage e;
            protected void readResponse(InputStream input) throws IOException  {
                e = EncodedImage.create(input);;
                if(e.getWidth() != placeholderImage.getWidth() || e.getHeight() != placeholderImage.getHeight()) {
                    ImageIO io = ImageIO.getImageIO();
                    if(io != null) {
                        ByteArrayOutputStream bo = new ByteArrayOutputStream();
                        io.save(new ByteArrayInputStream(e.getImageData()), bo, ImageIO.FORMAT_JPEG, placeholderImage.getWidth(), placeholderImage.getHeight(), 0.9f);
                        e = EncodedImage.create(bo.toByteArray());
                    }
                }
            }
            protected void postResponse() {
                rp.replace(e);
                getCache().put(key, e);
                inProgress.remove(key);
            }
        };
        cr.setPost(false);
        cr.setUrl(CloudStorage.getInstance().getUrlForCloudFileId(key));
        NetworkManager.getInstance().addToQueue(cr);
        return rp;
    }
    return image;
}
 
Example 17
Source File: ParseUploadCommand.java    From parse4cn1 with Apache License 2.0 5 votes vote down vote up
@Override
void setUpRequest(ConnectionRequest request) throws ParseException {
    setupDefaultHeaders();
    request.setPost(true);
    request.setHttpMethod("POST");
    request.setUrl(getUrl(endPoint, null));

    if (contentType != null) {
        addHeader(ParseConstants.HEADER_CONTENT_TYPE, contentType);
    }
}
 
Example 18
Source File: ParsePostCommand.java    From parse4cn1 with Apache License 2.0 5 votes vote down vote up
@Override
void setUpRequest(ConnectionRequest request) throws ParseException {
    setupDefaultHeaders();
    request.setPost(true);
    request.setHttpMethod("POST");
    request.setUrl(getUrl(endPoint, objectId));
}
 
Example 19
Source File: VServAds.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected Component getPendingAd() {
    if(imageURL == null) {
        return null;
    }
    if(renderNotify != null && renderNotify.length() > 0) {
        ConnectionRequest c = new ConnectionRequest();
        c.setFailSilently(true);
        c.setUrl(renderNotify);
        c.setPost(false);
        NetworkManager.getInstance().addToQueue(c);
    }
    if("image".equalsIgnoreCase(contentType)) {
        Button adComponent = new Button(){

            public void setIcon(Image icon) {
                if(icon != null && isScaleMode()){
                    icon = icon.scaledWidth(Display.getInstance().getDisplayWidth());
                }
                super.setIcon(icon);
            }
            
        };
        adComponent.setUIID("Container");
        adComponent.getStyle().setBgColor(backgroundColor);
        adComponent.getStyle().setOpacity(0xff);
        ImageDownloadService imd = new ImageDownloadService(imageURL, adComponent);
        NetworkManager.getInstance().addToQueueAndWait(imd);
        /*adComponent.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                Display.getInstance().execute(getAdDestination());
            }
        });*/
        return adComponent;
    } else {
        WebBrowser wb = new WebBrowser();
        if(wb.getInternal() instanceof BrowserComponent) {
            BrowserComponent bc = (BrowserComponent)wb.getInternal();
            bc.setBrowserNavigationCallback(new BrowserNavigationCallback() {
                public boolean shouldNavigate(final String url) {
                    unlock(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            Display.getInstance().execute(url);
                        }
                    });
                    return false;
                }
            });
        }
        wb.setURL(imageURL);
        return wb;
    }
}
 
Example 20
Source File: CloudStorage.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
private String uploadCloudFileImpl(String mimeType, String file, InputStream data, int dataSize) throws CloudException, IOException {
    String token = CloudPersona.getCurrentPersona().getToken();
    if(token == null || token.length() == 0) {
        if(!CloudPersona.createAnonymous()) {
            throw new CloudException(RETURN_CODE_FAIL_SERVER_ERROR, "Error creating anonymous login");
        }
        token = CloudPersona.getCurrentPersona().getToken();
    }
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl(SERVER_URL + "/fileStoreURLRequest");
    //req.addArgument("bb", Display.getInstance().getProperty("built_by_user", null));

    NetworkManager.getInstance().addToQueueAndWait(req);
    int rc = req.getResponseCode();
    if(rc != 200) {
        if(rc == 420) {
            throw new CloudException(RETURN_CODE_FAIL_QUOTA_EXCEEDED);
        }
        throw new CloudException(RETURN_CODE_FAIL_SERVER_ERROR);
    }

    String d = new String(req.getResponseData());
    MultipartRequest uploadReq = new MultipartRequest();
    uploadReq.setUrl(d);
    uploadReq.setManualRedirect(false);
    uploadReq.addArgument("bb", Display.getInstance().getProperty("built_by_user", null));
    uploadReq.addArgument("t", CloudPersona.getCurrentPersona().getToken());
    uploadReq.addArgument("pk", Display.getInstance().getProperty("package_name", null));
    if(data == null) {
        int pos = file.lastIndexOf('/');
        String shortName = file;
        if(pos > -1) {
            shortName = file.substring(pos);
        }
        uploadReq.addData(shortName, file, mimeType);
    } else {
        uploadReq.addData(file, data, dataSize, mimeType);
    }
    NetworkManager.getInstance().addToQueueAndWait(uploadReq);
    if(uploadReq.getResponseCode() != 200) {
        throw new CloudException(RETURN_CODE_FAIL_SERVER_ERROR);
    }
    String r = new String(uploadReq.getResponseData());
    if("ERROR".equals(r)) {
        throw new CloudException(RETURN_CODE_FAIL_SERVER_ERROR);
    }
    return r;
}