Created
January 17, 2019 21:08
-
-
Save LukeHackett/6532a97261e24ead6c23b7e96c82636c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.tinyproxy; | |
import org.apache.http.HttpHost; | |
import org.apache.http.client.config.RequestConfig; | |
import org.apache.http.client.methods.CloseableHttpResponse; | |
import org.apache.http.client.methods.HttpGet; | |
import org.apache.http.conn.HttpHostConnectException; | |
import org.apache.http.impl.client.CloseableHttpClient; | |
import org.apache.http.impl.client.HttpClients; | |
import org.apache.http.util.EntityUtils; | |
public class TinyProxyDemo { | |
public static void main(String[] args) throws Exception { | |
try (CloseableHttpClient client = HttpClients.createDefault()) { | |
HttpHost target = new HttpHost("jsonplaceholder.typicode.com", 443, "https"); | |
HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http"); | |
RequestConfig config = RequestConfig.custom() | |
.setProxy(proxy) | |
.build(); | |
HttpGet request = new HttpGet("/posts/42"); | |
request.setConfig(config); | |
System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy); | |
try (CloseableHttpResponse response = client.execute(target, request)) { | |
System.out.println("----------------------------------------"); | |
System.out.println(response.getStatusLine()); | |
System.out.println(EntityUtils.toString(response.getEntity())); | |
} catch (HttpHostConnectException e) { | |
if (e.getHost().equals(proxy)) { | |
System.out.println("Proxy " + proxy + " is unavailable, making request direct to " + target); | |
request.setConfig(null); | |
try (CloseableHttpResponse response = client.execute(target, request)) { | |
System.out.println("----------------------------------------"); | |
System.out.println(response.getStatusLine()); | |
System.out.println(EntityUtils.toString(response.getEntity())); | |
} | |
} else { | |
throw e; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment