1

I'm trying to create an url shortener app using google's url shortener api (https://developers.google.com/url-shortener/v1/getting_started#shorten). The problem is that I get a bad request. Here is the error: Error: Error downloading https://www.googleapis.com/urlshortener/v1/url - server replied: Bad Request

What did I do wrong? Here is the code:

void MainWindow::ppp(QString longurl)
{
    QNetworkAccessManager* manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *)));

    QUrl url = QUrl("https://www.googleapis.com/urlshortener/v1/url");

    QNetworkRequest request(url);
    request.setHeader(request.ContentTypeHeader,"application/json");

    QByteArray postData;
    postData.append("longUrl");
    postData.append(longurl);


    manager->post(request,postData);
}

void MainWindow::replyFinished(QNetworkReply *reply)
{
    if(reply->error() != QNetworkReply::NoError)
    {
        ui->textBrowser->setText("Error: " +  reply->errorString());
    }
    else
    {
        QByteArray responseData = reply->readAll();
        QString qstr(responseData);
        ui->textBrowser->setText(qstr);
    }
}
ddacot
  • 1,212
  • 3
  • 14
  • 40

2 Answers2

1
request.setHeader(request.ContentTypeHeader,"Content-Type: application/json");

Should be:

request.setHeader(request.ContentTypeHeader,"application/json");

And:

Youre sending json data. (Your header says so) So ypu have to format the postData as json. Also, you will have to set content-length.

Check this post

Community
  • 1
  • 1
trompa
  • 1,967
  • 1
  • 18
  • 26
  • Edited again, Check it. You have to format your post data as json. Sorry – trompa Jul 24 '13 at 09:22
  • Don't think wou can. Youll have to get the full json response and parse it for the info you want. Check http://qt-project.org/doc/qt-5.0/qtcore/json.html for qt5 / http://stackoverflow.com/questions/4169988/easiest-way-to-parse-json-in-qt-4-7 for qt4 – trompa Jul 24 '13 at 09:54
1

You have to send your post data in json format.

To make your code work, replace

QByteArray postData;
postData.append("longUrl");
postData.append(longurl);

with this

QByteArray postData;
postData.append("{\"longUrl\": \""+longurl+"\"}");
zahirdhada
  • 405
  • 4
  • 14