パラメータをステッチHTTP GETリクエストを構築する方法

参考:https://www.cnblogs.com/honeybee/p/7879705.html

 

HttpClient4.Xスプライシング取得要求送信パラメータ

  HttpClientをがGETリクエストを送信使用する場合は、リクエストパラメータができますか?キー=ヴァル&キー1 = val1とスプライスリアURLへ。
しかし、より多くのリクエストパラメータは、この方法はあまりにも面倒で、非常にエレガントではありません。いくつかの研究は、HttpClient4.X自体が見つから
パラメータを処理してサポートされています。

1.リクエストURIはURIBuilderを使用して構築しました

ジャーパッケージHTTPClientの関連MVN依存性:

< 依存性> 
    < のgroupId > org.apache.httpcomponents </ のgroupId > 
    < たartifactId > httpcore </ たartifactId > 
    < バージョン> 4.4.3 </ バージョン> 
</ 依存> 
< 依存性> 
    < のgroupId > org.apache.httpcomponents </ groupId > 
    < たartifactId > HTTPClientの</ たartifactId > 
    < バージョン>4.5.1</ バージョン> 
</ 依存関係>
輸入com.google.common.collect.Lists。
輸入org.apache.http.Consts。
輸入org.apache.http.HttpEntity。
輸入org.apache.http.HttpStatus;
輸入org.apache.http.NameValuePair;
輸入org.apache.http.client.config.RequestConfig;
輸入org.apache.http.client.entity.UrlEncodedFormEntity。
輸入org.apache.http.client.methods.CloseableHttpResponse。
輸入org.apache.http.client.methods.HttpGet;
輸入org.apache.http.client.utils.URIBuilder。
輸入org.apache.http.impl.client.CloseableHttpClient;
インポートorg.apache.http.impl.client.HttpClients;
輸入org.apache.http.message.BasicNameValuePair;
輸入org.apache.http.util.EntityUtils。

    プライベート HTTPGET buildHttpGet(文字列のURL、地図<文字列、文字列> パラ)
             スローURISyntaxExceptionを{
        URIBuilderビルダー = 新しいURIBuilder(URL);
        セットの<string>セット= para.keySet()。
        {(セット文字列キー)
            builder.setParameter(キー、para.get(キー));
        }
        HTTPGET要求 = 新しいHTTPGET(builder.build());
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout( 6000 
                .setConnectTimeout( 6000 
                .setConnectionRequestTimeout( 6000 ))(.build。
        request.setConfig(requestConfig)。
        System.out.println(request.getURI()のtoString())。
        リターン要求。
    }

 

スプライスURIに2.のNameValuePair

リスト<のNameValuePair>のparams = Lists.newArrayList();
params.add( BasicNameValuePair( "cityEname"、 "河南" ));
STR文字列 = "" ;
 // 変換キーと値のペア 
STR = EntityUtils.toString(新新UrlEncodedFormEntity(パラメータ、Consts.UTF_8));
System.out.println(STR)。
HTTPGET HTTPGET = 新しい HTTPGET(URL + + STR "?");

 

3.リバースHTTPGETに応じて、キーと値のペアのリストを取得します

HTTPGET要求=  HTTPGET( "http://example.com/?var=1&var=2" );
NewBuilder UriBuilder = 新新UriBuilder(request.getURI());
 //は、キーと値のペアのリストを取得 
一覧<NameValuePairsの>のparams = newBuilder.getQueryParams()を;
 // 変換キー文字列 
文字列STR = EntityUtils.toString(新新 UrlEncodedFormEntity (paramsは、Consts.UTF_8))。

おすすめ

転載: www.cnblogs.com/duguxiaobiao/p/12092011.html