我需要通过代理身份验证从API服务器获取API响应内容到我的本地服务器。 API请求将如下:
http://api.example.com/nav_page/head?locale=in&pointer=old&cont=/resque/&scope=old&release=new
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class ClientProxyAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("proxy.example.com", 8080),
new UsernamePasswordCredentials("Domain\user", "pass"));
HttpHost targetHost = new HttpHost("api.example.com", 80, "http");
HttpHost proxy = new HttpHost("proxy.example.com", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("via proxy: " + proxy);
System.out.println("to target: " + targetHost);
HttpResponse response = httpclient.execute(targetHost, httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
System.out.println(EntityUtils.toString(entity));
}
Header[] headers = response.getAllHeaders();
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
在此代码中,如果目标URL指定为api.example.com,则身份验证成功并获取资源(但基础目录中没有资源,因此没有任何有用的接收)。但要获得正确的响应,我需要在该主机内部提供导航路径。
因此,如果我追加像
这样的路径HttpHost targetHost = new HttpHost("api.example.com/nav_page/head?locale=in&pointer=old&cont=/resque/&scope=old&release=new", 80, "http");
我收到了一些错误回复,但不正确。
HTTP/1.1 503 Service Unavailable
Response content length: 442
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>503 Service Temporarily Unavailable</title>
</head><body>
<h1>Service Temporarily Unavailable</h1>
<p>The server is temporarily unable to service your
request due to maintenance downtime or capacity
problems. Please try again later.</p>
<p>Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.</p>
</body></html>
如果我直接在浏览器中点击URL,我就能得到回复。
我可以知道如何发送导航路径的请求吗?