Reputation: 3
I have the following code which uses google URL shortening service. The code runs just fine but when run with the proxy it returns a unknown host exception Is there a way to hit http://www.googleapis.com with authentication through my code .
I have used the following code:
String json = "{\"longUrl\": \""+longUrl+"\"}";
String apiURL = GOOGLE_URL_SHORT_API+"?key="+GOOGLE_API_KEY;
System.setProperty("proxySet", "true");
System.setProperty("http.proxyHost", proxyHost);
System.setProperty("http.proxyPort", proxyPort);
AuthCacheValue.setAuthCache(new AuthCacheImpl());
Authenticator.setDefault(new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(proxyUser,proxyPassword.toCharArray());
}
});
HttpPost postRequest = new HttpPost(apiURL);
postRequest.setHeader("Content-Type", "application/json");
postRequest.setEntity(new StringEntity(json, "UTF-8"));
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(postRequest);
String responseText = EntityUtils.toString(response.getEntity());
Gson gson = new Gson();
@SuppressWarnings("unchecked")
HashMap<String, String> res = gson.fromJson(responseText, HashMap.class);
Need suggestions.
Upvotes: 0
Views: 502