Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Native Development

Reply
Trusted Contributor
AllSystemGo
Posts: 140
Registered: ‎11-23-2010
My Device: Torch 9800
Accepted Solution

Need to connect to a https site

[ Edited ]

Hello everyone,

 

   I would like to be able to connect to a HTTPS website that returns json for me to use in an App I'm creating. Right now I was using this example to help me out on the logic of things : http://supportforums.blackberry.com/t5/Cascades-Development/Method-for-making-an-HTTP-style-request-...

 

The problem with this example is that it connects to a simple HTTP site and when I use it for my site it returns a Error: SSL handshake failed.

 

Can anyone help me out figuring out what I am missing.

 

Thank you for the help

 

 

UPDATE : 

 

Ok so here's what I added to my code based on the solution on that post: http://supportforums.blackberry.com/t5/Native-Development/Problem-with-HTTPS-on-Simulator/td-p/17754...

 

So, same code as the TwitterApp Selom explain in the first link, then added after the req has been made in the TwitterRequest.cpp in the getTimeline function

 

QString queryUri = "https://somesite/get?username=" + username
			+ "&password=" + password;
	//qDebug() << queryUri;
	QUrl url(queryUri);
	QNetworkRequest req(url);

	QSslConfiguration config = req.sslConfiguration();
	config.setPeerVerifyMode(QSslSocket::VerifyNone);
	config.setProtocol(QSsl::TlsV1);
	req.setSslConfiguration(config);

	QNetworkReply* ipReply = netManager->get(req);
	connect(ipReply, SIGNAL(finished()), this, SLOT(onTimelineReply()));

 

So now I don't get that error anymore but I get a blank listview... Is there anything else missing? 

 

 

UPDATE 2:

 

Ok so I've put a couple of qDebug here and there and I see that my response is getting populated with the json. Now it doesn't show in my listview. I'll keep you updated.

BlackBerry Development Advisor (Retired)
smacmartin
Posts: 499
Registered: ‎05-07-2012
My Device: developer

Re: Need to connect to a https site

Did you get the list populated?

See sample apps stampcollector and weatherguesser.

A typical issue is just implementing function itemType(data, indexPath) to line up with your ListItemComponents.  If you are stuck, can you post the offending qml and C++; perhaps we can help.

 

Stuart

Trusted Contributor
AllSystemGo
Posts: 140
Registered: ‎11-23-2010
My Device: Torch 9800

Re: Need to connect to a https site

Thank you for the quick answer. I'm reviewing my code before I post it here for some help.

Trusted Contributor
AllSystemGo
Posts: 140
Registered: ‎11-23-2010
My Device: Torch 9800

Re: Need to connect to a https site

Ok So I think I narrow it down to this

 

    if (!success)
    {
    	qDebug() << "Error retrieving twitter fee: " << info;
    	return;
    }

    ListView* list = m_root->findChild<ListView*>("basicTimelineView");
    if (!list || list->dataModel() != NULL)
    {
        qDebug() << "basic list already populated";
        return; //if basic timeline list not found or already populated do nothing
    }

    // Create a group data model with id as the sorting key
    GroupDataModel* dm = new GroupDataModel(QStringList() << "item_id");
    dm->setGrouping(ItemGrouping::None);

    // parse the json response with JsonDataAccess
    bb::data::JsonDataAccess ja;
    QVariant jsonva = ja.loadFromBuffer(info);

    // the qvariant is an array of tweets which is extracted as a list
    QVariantList feed = jsonva.toList();

    qDebug() << "Feed: ";
    qDebug() << feed[0];

    // for each object in the array, push the variantmap in its raw form
    // into the ListView
    for (QList<QVariant>::iterator it = feed.begin(); it != feed.end(); it++)
    {
        QVariantMap tweet = it->toMap();
        dm->insert(tweet);
    }

    // set the data model to display
    list->setDataModel(dm);
    list->setVisible(true);

 Ok so basically I get to the part were my json get parsed. I guess for some reason mine is getting parsed worng cause that's what I get in the jsonva variable

 

QVariant(QVariantMap, QMap(("complete", QVariant(qlonglong, 1) ) ( "list" ,  QVariant(QVariantMap, QMap(("176525329", QVariant(QVariantMap, QMap(("item_id", QVariant(QString, "176525329") ) ( "state" ,  QVariant(QString, "0") ) ( "time_added" ,  QVariant(QString, "1339115647") ) ( "time_updated" ,  QVariant(QString, "1341374463") ) ( "title" ,  QVariant(QString, "QML/Cascades tip of the day: Managing Properties of an Existing Component «") ) ( "url" ,  QVariant(QString, "http://devblog.blackberry.com/2012/06/cascades-tip-qml/?CPID=E10C020") ) )  ) ) ( "186696467" ,  QVariant(QVariantMap, QMap(("item_id", QVariant(QString, "186696467") ) ( "state" ,  QVariant(QString, "0") ) ( "time_added" ,  QVariant(QString, "1341283055") ) ( "time_updated" ,  QVariant(QString, "1341283055") ) ( "title" ,  QVariant(QString, "Is the Nexus Q Worth Buying?") ) ( "url" ,  QVariant(QString, "http://lifehacker.com/5922854/is-the-nexus-q-worth-buying") ) )  ) ) )  ) ) ( "since" ,  QVariant(qlonglong, 1341374463) ) ( "status" ,  QVariant(qlonglong, 1) ) )  )

 

I'm quite confused why it doens't parse like the TwitterFeeds. Hope you guys understand and can help me out understand.

 

Thank you

BlackBerry Development Advisor (Retired)
smacmartin
Posts: 499
Registered: ‎05-07-2012
My Device: developer

Re: Need to connect to a https site

I didn't debug it, merely playing computer...

 

Are you sure you want to convert the map to a feed?  Looks to me like feed should be empty because the conversion to list should fail and return an empty list.

 

I'm not 100% sure which data you want to extract from this and display, but I'm guessing some contents within "list"?  It might be easier to draw a diagram of the data you got back.  If it's not the data you expect, perhaps there's an error in how you populate "info".  If it is the data you should be getting back, you have to do all the "is it a map?"  "is it a list?" double-checking, and extract the data you want to display.

 

The next step will be making sure the data in the model matches what the ListItemComponent handles.

 

Let me know if this helps (or not)

 

Stuart

Trusted Contributor
AllSystemGo
Posts: 140
Registered: ‎11-23-2010
My Device: Torch 9800

Re: Need to connect to a https site

[ Edited ]

Honestly I'm pretty confused too... I guess I don't understand json file as I thought I was. So if you can enlight me about it pls do. I'll explain what I'm trying to achieve. 

 

 Right now I have these classes

 

app.cpp

#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/GroupDataModel>
#include <bb/cascades/ListView>
#include <bb/data/jsondataaccess>

#include "App.hpp"
#include "TwitterRequest.hpp"

using namespace bb::cascades;

App::App()
{
    QmlDocument *qml = QmlDocument::create("main.qml");
    qml->setContextProperty("cs", this);

    m_root = qml->createRootNode<AbstractPane>();
    Application::setScene(m_root);
}

void App::getTimeline(QString username, QString password)
{
    TwitterRequest* tr = new TwitterRequest();
    tr->getTimeline(username, password);
    connect(tr, SIGNAL(complete(QString, bool)), this, SLOT(onTwitterTimeline(QString, bool)));
}

void App::onTwitterTimeline(QString info, bool success)
{
    if (!success)
    {
    	qDebug() << "Error retrieving twitter fee: " << info;
    	return;
    }

    qDebug() << "Info: " + info;

    ListView* list = m_root->findChild<ListView*>("basicTimelineView");
    if (!list || list->dataModel() != NULL)
    {
        qDebug() << "basic list already populated";
        return; //if basic timeline list not found or already populated do nothing
    }

    // Create a group data model with id as the sorting key
    GroupDataModel* dm = new GroupDataModel(QStringList() << "item_id");
    dm->setGrouping(ItemGrouping::None);

    // parse the json response with JsonDataAccess
    bb::data::JsonDataAccess ja;
    QVariant jsonva = ja.loadFromBuffer(info);

    // the qvariant is an array of tweets which is extracted as a list
    QVariantMap feed = jsonva.toMap();

    dm->insert(feed);

    // set the data model to display
    list->setDataModel(dm);
    list->setVisible(true);
}

 

NetworkRequest

/*
 * Copyright (c) 2011-2012 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "TwitterRequest.hpp"
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDebug>
#include <QSslConfiguration>

TwitterRequest::TwitterRequest() {
}

TwitterRequest::~TwitterRequest() {
}

void TwitterRequest::getTimeline(QString username, QString password) {
	QNetworkAccessManager* netManager = new QNetworkAccessManager();
	if (!netManager) {
		qDebug() << "Unable to create QNetworkAccessManager!";
		emit complete("Unable to create QNetworkAccessManager!", false);
		return;
	}

	QString queryUri = "https://somewebsiteget?username=" + username
			+ "&password=" + password";
	qDebug() << queryUri;
	QUrl url(queryUri);
	QNetworkRequest req(url);

	QSslConfiguration config = req.sslConfiguration();
	config.setPeerVerifyMode(QSslSocket::VerifyNone);
	config.setProtocol(QSsl::TlsV1SslV3);
	req.setSslConfiguration(config);

	QNetworkReply* ipReply = netManager->get(req);
	connect(ipReply, SIGNAL(finished()), this, SLOT(onTimelineReply()));
}

void TwitterRequest::onTimelineReply() {
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
	QString response;
	bool success = false;
	if (reply) {
		if (reply->error() == QNetworkReply::NoError) {
			int available = reply->bytesAvailable();
			if (available > 0) {
				int bufSize = sizeof(char) * available + sizeof(char);
				QByteArray buffer(bufSize, 0);
				int read = reply->read(buffer.data(), available);
				response = QString(buffer);
				success = true;
			}
		} else {
			response =
					QString("Error: ") + reply->errorString()
							+ QString(" status:")
							+ reply->attribute(
									QNetworkRequest::HttpStatusCodeAttribute).toString();
			qDebug() << response;
		}
		reply->deleteLater();
	}
	if (response.trimmed().isEmpty()) {
		response = "Twitter request failed. Check internet connection";
		qDebug() << response;
	}
	emit complete(response, success);
}

 

and my main.qml

 

import bb.cascades 1.0

Page {
    content: Container {
        background: Color.DarkBlue
        layout: DockLayout {
        }
        ListView {
            layoutProperties: DockLayoutProperties {
                verticalAlignment: VerticalAlignment.Center
            }
            objectName: "basicTimelineView"
            id: basicTimelineView
            listItemComponents: [
                ListItemComponent {
                    type: "item"
                    StandardListItem {
                        descriptionText: {
                            ListItemData.title
                        }
                    }
                }
            ]
        }
    }
    onCreationCompleted: {
        cs.getTimeline ("username", "password");
    }
}

 

Thank you again for your help.

 

UPDATE: 

 

BTW I just want to add that I'm pretty new to this so I'm doing my best to understand, what I did here was just to test out if everything was working ( if I could retrieve my data and list the title and url in a ListView). I used the TwitterRequest from Selom to try an achieve that but I'm going to rewrite everything to fit my project. I'm not just adapting everything to my needs.

BlackBerry Development Advisor (Retired)
smacmartin
Posts: 499
Registered: ‎05-07-2012
My Device: developer

Re: Need to connect to a https site

I'm not going to get a chance to look through this in detail today, so I'll give a hint of where I think the problem is to see if it unblocks you.

 

I think what I replied before is correct, but not clear enough.

 

You get a QVariant.   This wraps a blob.   If it's a list, you can convert it to a list (otherwise you'll get an empty list).  If it's a map (a bunch of name-value pairs) then you can convert it to a map; if you try to convert to a map and it's not a map, you get an empty map.

 

In your case, you get a bunch of name-value pairs.

Your original code then said:  "Convert this to a list, but if it's not a list give me an empty list".

 

The computer says, "okey dokey.  I have a map, so here's your empty list."

 

Is that any clearer?   The issue is not with JSON.  It's with pulling out the information in these QVariants.

Computer: "Here's a thing"

You: "what kind of thing?"  (there's a method to get the type you can switch on)

-or-  "Is it a map?"   (there's a routine to test if it can be converted to a specific type)

 

Is this clearer?   Leave the JSON alone for the moment and look at the data you received.

 

Stuart

Trusted Contributor
AllSystemGo
Posts: 140
Registered: ‎11-23-2010
My Device: Torch 9800

Re: Need to connect to a https site

[ Edited ]

Yep I think you are right. But I don't know if answering me like a child was your intention or you just thought I was a moron,  but at least I try to understand stuff. Granted I don't understand alot but still on my first post I said that I was just starting . Either ways you manage to help so I am gratefull. 

 

And BTW I didn't want me to make my app, I can do it myself just needed a little bit of guidance.

 

Thank you

 

PS2: there is 60 other ppl that looked my post and didn't reply, so I guess that question wasn't as easy to answer.

 

Thank you for you help it's really appreciated.

BlackBerry Development Advisor (Retired)
smacmartin
Posts: 499
Registered: ‎05-07-2012
My Device: developer

Re: Need to connect to a https site

Sometimes there's clarity in a bit of silliness.

I was in an odd mood and had fun with it.

No offense intended :smileyhappy:

 

Stuart