QGIS API Documentation 3.41.0-Master (45a0abf3bec)
Loading...
Searching...
No Matches
qgsalgorithmhttprequest.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmhttprequest.cpp
3 ---------------------
4 begin : September 2024
5 copyright : (C) 2024 by Dave Signer
6 email : david at opengis dot ch
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19#include "moc_qgsalgorithmhttprequest.cpp"
21#include "qgis.h"
22
24#include <QUrl>
25#include <QNetworkRequest>
26#include <QDesktopServices>
27#include <QUrlQuery>
28#include <QMimeDatabase>
29
31
32QString QgsHttpRequestAlgorithm::name() const
33{
34 return QStringLiteral( "httprequest" );
35}
36
37QString QgsHttpRequestAlgorithm::displayName() const
38{
39 return tr( "HTTP(S) POST/GET request" );
40}
41
42QString QgsHttpRequestAlgorithm::shortDescription() const
43{
44 return tr( "Performs a HTTP(S) POST/GET request and returns the result code, error message and the data" );
45}
46
47QStringList QgsHttpRequestAlgorithm::tags() const
48{
49 return tr( "open,url,internet,url,fetch,get,post,request,https,http,download" ).split( ',' );
50}
51
52QString QgsHttpRequestAlgorithm::group() const
53{
54 return tr( "File tools" );
55}
56
57QString QgsHttpRequestAlgorithm::groupId() const
58{
59 return QStringLiteral( "filetools" );
60}
61
62QString QgsHttpRequestAlgorithm::shortHelpString() const
63{
64 return tr( "This algorithm performs a HTTP(S) POST/GET request and returns the HTTP status code and the reply data.\n"
65 "If an error occurs then the error code and the message will be returned.\n\n"
66 "Optionally, the result can be written to a file on disk.\n\n"
67 "By default the algorithm will warn on errors. Optionally, the algorithm can be set to treat HTTP errors as failures." );
68}
69
70QgsHttpRequestAlgorithm *QgsHttpRequestAlgorithm::createInstance() const
71{
72 return new QgsHttpRequestAlgorithm();
73}
74
75void QgsHttpRequestAlgorithm::initAlgorithm( const QVariantMap & )
76{
77 addParameter( new QgsProcessingParameterString( QStringLiteral( "URL" ), tr( "URL" ), QVariant(), false, false ) );
78
79 std::unique_ptr< QgsProcessingParameterEnum > methodParam = std::make_unique < QgsProcessingParameterEnum > (
80 QStringLiteral( "METHOD" ),
81 QObject::tr( "Method" ),
82 QStringList()
83 << QStringLiteral( "GET" )
84 << QStringLiteral( "POST" ),
85 false,
86 0
87 );
88 methodParam->setHelp( QObject::tr( "The HTTP method to use for the request" ) );
89 addParameter( methodParam.release() );
90
91 std::unique_ptr< QgsProcessingParameterString > dataParam = std::make_unique < QgsProcessingParameterString >(
92 QStringLiteral( "DATA" ), tr( "POST data" ), QVariant(), false, true );
93 dataParam->setHelp( QObject::tr( "The data to add in the body if the request is a POST" ) );
94 addParameter( dataParam.release() );
95
96 std::unique_ptr< QgsProcessingParameterFileDestination > outputFileParam = std::make_unique < QgsProcessingParameterFileDestination >(
97 QStringLiteral( "OUTPUT" ), tr( "File destination" ), QObject::tr( "All files (*.*)" ), QVariant(), true, false );
98 outputFileParam->setHelp( tr( "The result can be written to a file instead of being returned as a string" ) );
99 addParameter( outputFileParam.release() );
100
101 std::unique_ptr< QgsProcessingParameterAuthConfig > authConfigParam = std::make_unique < QgsProcessingParameterAuthConfig >(
102 QStringLiteral( "AUTH_CONFIG" ), tr( "Authentication" ), QVariant(), true );
103 authConfigParam->setHelp( tr( "An authentication configuration to pass" ) );
104 addParameter( authConfigParam.release() );
105
106 std::unique_ptr< QgsProcessingParameterBoolean > failureParam = std::make_unique < QgsProcessingParameterBoolean >(
107 QStringLiteral( "FAIL_ON_ERROR" ), tr( "Consider HTTP errors as failures" ), false );
108 failureParam->setHelp( tr( "If set, the algorithm will fail on encountering a HTTP error" ) );
109 addParameter( failureParam.release() );
110
111 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "ERROR_CODE" ), QObject::tr( "Network error code" ) ) );
112 addOutput( new QgsProcessingOutputString( QStringLiteral( "ERROR_MESSAGE" ), QObject::tr( "Network error message" ) ) );
113 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "STATUS_CODE" ), QObject::tr( "HTTP status code" ) ) );
114 addOutput( new QgsProcessingOutputString( QStringLiteral( "RESULT_DATA" ), QObject::tr( "Reply data" ) ) );
115}
116
117QVariantMap QgsHttpRequestAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
118{
119 const QString url = parameterAsString( parameters, QStringLiteral( "URL" ), context );
120 if ( url.isEmpty() )
121 throw QgsProcessingException( tr( "No URL specified" ) );
122 const Qgis::HttpMethod httpMethod = static_cast< Qgis::HttpMethod>( parameterAsEnum( parameters, QStringLiteral( "METHOD" ), context ) );
123 const QString data = parameterAsString( parameters, QStringLiteral( "DATA" ), context );
124 const QString authCfg = parameterAsString( parameters, QStringLiteral( "AUTH_CONFIG" ), context );
125 const QString outputFile = parameterAsFileOutput( parameters, QStringLiteral( "OUTPUT" ), context );
126 const bool failOnError = parameterAsBool( parameters, QStringLiteral( "FAIL_ON_ERROR" ), context );
127 const QUrl qurl = QUrl::fromUserInput( url );
128
129 // Make Request
130 QNetworkRequest request( qurl );
131 QgsBlockingNetworkRequest blockingRequest;
132 blockingRequest.setAuthCfg( authCfg );
134
135 switch ( httpMethod )
136 {
138 {
139 errorCode = blockingRequest.get( request );
140 break;
141 }
143 {
144 errorCode = blockingRequest.post( request, data.toUtf8() );
145 break;
146 }
147 }
148
149 // Handle reply
150 const int statusCode = blockingRequest.reply().attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt();
151 QString errorMessage = QString();
152 QByteArray resultData = QByteArray();
153
154 if ( errorCode == QgsBlockingNetworkRequest::NoError )
155 {
156 feedback->pushInfo( tr( "Request succeeded with code %1" ).arg( statusCode ) );
157 resultData = blockingRequest.reply().content();
158
159 if ( !outputFile.isEmpty() )
160 {
161 QFile tempFile( outputFile );
162 tempFile.open( QIODevice::WriteOnly );
163 tempFile.write( resultData );
164 tempFile.close();
165
166 feedback->pushInfo( tr( "Result data written to %1" ).arg( outputFile ) );
167 }
168 }
169 else
170 {
171 feedback->pushInfo( tr( "Request failed with code %1" ).arg( statusCode ) );
172 errorMessage = blockingRequest.reply().errorString();
173 if ( failOnError )
174 {
175 throw QgsProcessingException( errorMessage );
176 }
177 feedback->pushWarning( errorMessage );
178 }
179
180 QVariantMap outputs;
181 outputs.insert( QStringLiteral( "STATUS_CODE" ), statusCode );
182 outputs.insert( QStringLiteral( "ERROR_CODE" ), errorCode );
183 outputs.insert( QStringLiteral( "ERROR_MESSAGE" ), errorMessage );
184 outputs.insert( QStringLiteral( "RESULT_DATA" ), QString( resultData ) );
185 outputs.insert( QStringLiteral( "OUTPUT" ), outputFile );
186 return outputs;
187}
188
HttpMethod
Different methods of HTTP requests.
Definition qgis.h:971
@ Post
POST method.
@ Get
GET method.
A thread safe class for performing blocking (sync) network requests, with full support for QGIS proxy...
ErrorCode post(QNetworkRequest &request, QIODevice *data, bool forceRefresh=false, QgsFeedback *feedback=nullptr)
Performs a "post" operation on the specified request, using the given data.
void setAuthCfg(const QString &authCfg)
Sets the authentication config id which should be used during the request.
ErrorCode get(QNetworkRequest &request, bool forceRefresh=false, QgsFeedback *feedback=nullptr, RequestFlags requestFlags=QgsBlockingNetworkRequest::RequestFlags())
Performs a "get" operation on the specified request.
@ NoError
No error was encountered.
QgsNetworkReplyContent reply() const
Returns the content of the network reply, after a get(), post(), head() or put() request has been mad...
QVariant attribute(QNetworkRequest::Attribute code) const
Returns the attribute associated with the code.
QString errorString() const
Returns the error text for the reply, or an empty string if no error was encountered.
QByteArray content() const
Returns the reply content.
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
A numeric output for processing algorithms.
A string output for processing algorithms.
A string parameter for processing algorithms.