我想访问我的网站,首先需要基本授权,然后将参数(搜索关键字)发布到我的主页。
我的代码可以通过基本授权并获得响应文本,但是我无法获得搜索结果,而是获得主页代码。
因此,我打印了 parameters.size() 并返回 0,所以我怀疑 HttpClient 重定向方法在基本授权后没有传递参数。
按照我的代码,它试图获取搜索结果:
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("search_keyword", "test"));
params.add(new BasicNameValuePair("search_size", "50"));
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
boolean isRedirect=false;
try {
isRedirect = super.isRedirected(request, response, context);
} catch (ProtocolException e) {
throw e;
}
if (!isRedirect) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 301 || responseCode == 302) {
return true;
}
}
return isRedirect;
}
});
String encoding = Base64Encoder.encode("admin:password");
HttpPost httppost = new HttpPost("http://127.0.0.1/MySystem/home");
httppost.setHeader("Authorization", "Basic " + encoding);
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case HttpURLConnection.HTTP_OK:
HttpEntity entity = response.getEntity();
List<NameValuePair> parameters = new ArrayList<NameValuePair>(URLEncodedUtils.parse(entity));
System.out.println("parameters size: "+parameters.size());
for(NameValuePair p:parameters)
System.out.println("parameter: "+ p.getName() + p.getValue());
if(entity != null) {
responseText = EntityUtils.toString(entity);
System.out.println("responseText: ");
System.out.println(responseText);
}
break;
default:
throw new Exception("Failed to pass the basic authorization. Response code: "+responseCode);
}
更新:
以下条件将返回 true:
if (responseCode == 301 || responseCode == 302) {
return true;
}