Issue
I am working to modernize old legacy code, and while doing that ran into some deprecated constructs that I can't figure out how to handle. They all look somewhat like this:
HttpPost oauthVerificationRequest = new HttpPost(authURL);
oauthVerificationRequest.getParams().setParameter(OAUTH_TOKEN_KEY, oauthToken);
HttpResponse oauthVerificationRequestResponse = client.getHttpClient().execute(oauthVerificationRequest);
There, my IDE complains that both getParams()
as well as setParameter
is deprecated.
The thing is, written as it is like this, I understand exactly what is happening. The deprecated line sets the value of the parameter with the key OAUTH_TOKEN_KEY
of the request to the value of oauthToken
, and probably creates it if it doesn't exist.
However, even knowing that this is what is supposed to happen in this line, I have been unable to find a way to write this line in a modern way. I've tried to figure it out, but the new way of constructing a AbstractHttpMessage simply confuses me.
Since I learn best by examples, could someone please provide me with a "translation" of the above code to the new logic?
Solution
Okay, once again it seems that writing down my thoughts as a question helped get my mind down on the right track to find the solution. So to answer my own question, the correct way to write above statement in the new logic would be:
URIBuilder oauthVerificationRequestBuilder = new URIBuilder(authUrl);
oauthVerificationRequestBuilder.setParameter(OAUTH_TOKEN_KEY, oauthToken);
HttpPost oauthVerificationRequest = new HttpPost(oauthVerificationRequestBuilder.build());
HttpResponse oauthVerificationRequestResponse = client.getHttpClient().execute(oauthVerificationRequest);
So basically, you first create a builder, then set the parameters inside the builder, and then create the request using builder.build()
as its parameter.
Bonus Question:
Is there also a way to get the addHeader()
modification into the builder? Because right now, the entire construct looks like this for me, and it feels kinda inconsistent to use the builder for the parameters, and then slapping the header on top of the request the "old fashioned" way:
URIBuilder oauthVerificationRequestBuilder = new URIBuilder(authUrl);
oauthVerificationRequestBuilder.setParameter(OAUTH_TOKEN_KEY, oauthToken);
oauthVerificationRequestBuilder.setParameter(OAUTH_VERIFIER_KEY, oauthVerifier);
oauthVerificationRequestBuilder.setParameter(AUTHORIZE_KEY, VALUE_STRING_TRUE);
HttpPost oauthVerificationRequest = new HttpPost(oauthVerificationRequestBuilder.build());
oauthVerificationRequest.addHeader(CONTENT_TYPE_KEY, CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED_UTF_8);
Answered By - Kira Resari