使用HttpClient访问http地址,有时候会报302错误。
通过上网搜索,发现问题所在,报302是因为访问的http地址在服务端做了访问重定向,需要请求重定向后的URI。
1.简单实例,http访问返回302,此时需要获取重定向地址,继续进行重定向访问,以获取最终结果:
public class TestLogin {
public static void main(String args[]) {
try {
HttpClient client = HttpClients.createDefault();
login(client);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void login(HttpClient client) throws Exception {
final String APPLICATION_JSON = "application/json";
final String CONTENT_TYPE_TEXT_JSON = "text/json";
String url = "http://172.16.30.208:8092/svc/login";
String js = "{\"username\":\"13800000002\",\"password\":\"123456\"}";
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity se = new StringEntity(js);
se.setContentType(CONTENT_TYPE_TEXT_JSON);
httpPost.setEntity(se);
HttpResponse response = null;
response = client.execute(httpPost);
//----------判断是否重定向开始
int code = response.getStatusLine().getStatusCode();
String newuri = "";
if (code == 302) {
Header header = response.getFirstHeader("location"); // 跳转的目标地址是在 HTTP-HEAD 中的
newuri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请,以便得到跳转后的信息是啥。
System.out.println(newuri);
System.out.println(code);
httpPost = new HttpPost(newuri);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
se = new StringEntity(js);
se.setContentType(CONTENT_TYPE_TEXT_JSON);
httpPost.setEntity(se);
response = client.execute(httpPost);
code = response.getStatusLine().getStatusCode();
System.out.println("login" + code);
}
//------------重定向结束
HttpEntity entity = null;
entity = response.getEntity();
String s2 = EntityUtils.toString(entity, "UTF-8");
System.out.println(s2);
}
}
2.复杂实例,来自网络:
需要引导用户打开授权页面进行授权
1). 直接获取数据,传递用户账号;
2). 没有登陆直接去访问会跳转到登陆页面;
3). 登陆了之后,会有个授权页面,需要手动去点击授权按钮才真正跳转;
/**
* <pre>
* 模拟需要登陆之后才能访问第三方网站
* 并且需要一些人工参与的操作
* </pre>
*/
public class Test {
private String userName = "我是用户名";
private String password = "我是密码";
public void loginNext() throws IOException {
BasicCookieStore cookieStore = new BasicCookieStore();
// 全局用这一个httpClient对象模拟真实的一个浏览器中操作
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
try {
// 模拟用户登录
HttpPost httpLogin = new HttpPost("xxxxxxxxxxxxxx/index.php/auth/auth/login");// 指向一个没有验证码的登录页面
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("username", userName));// 用户名对应的key
nvps.add(new BasicNameValuePair("password", MD5Coder.md5Encode(password)));// 密码对应的key
httpLogin.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse respLogin = httpClient.execute(httpLogin);
try {
HttpEntity entity = respLogin.getEntity();
out.println("respLogin------------>>" + respLogin.toString());
out.println("Login form get: " + respLogin.getStatusLine());
EntityUtils.consume(entity);
out.println("Initial set of cookies:");
List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {
out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
out.println("Cookie-" + i + "==" + cookies.get(i).toString());
}
}
} finally {
respLogin.close();
}
// 利用会话保持,继续访问目标地址
HttpGet httpGetAuth = new HttpGet("xxxxxxxxxxxxxxx/index.php/Auth/Auth/auth?app_id=xxxxxx&redirect_uri=回调地址&response_type=code");
CloseableHttpResponse respAuth = httpClient.execute(httpGetAuth);
String entityAuthStr = "";
try {
out.println(respAuth.getStatusLine());
HttpEntity entityAuth = respAuth.getEntity();
entityAuthStr = EntityUtils.toString(entityAuth);
out.println("get Auth cookies:");
List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {
out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
out.println("- " + cookies.get(i).toString());
}
}
out.println("访问目标地址的结果--------------------->>" + entityAuthStr);//把结果打印出来看一下
EntityUtils.consume(entityAuth);
} finally {
respAuth.close();
}
// 解析登陆之后访问目标地址的html页面 获取目标form表单元素
Document doc = Jsoup.parseBodyFragment(entityAuthStr);
String title = doc.title();
out.println("title-------->>" + title);
Element element = doc.body();
Elements form = element.select("[name='authForm']");// 授权的form表单
out.println(form);
String actionUrl = form.attr("action");
String app_id = element.select("[name='app_id']").val();
String redirect_uri = element.select("[name='redirect_uri']").val();
String state = element.select("[name='state']").val();
String key = element.select("[name='key']").val();
String format = element.select("[name='format']").val();
// 利用会话保持,继续模拟点击授权按钮 提交form表单
HttpPost httpPostGetCode = new HttpPost(actionUrl);
List<NameValuePair> nvps2 = new ArrayList<>();
nvps2.add(new BasicNameValuePair("app_id", app_id));
nvps2.add(new BasicNameValuePair("redirect_uri", redirect_uri));
nvps2.add(new BasicNameValuePair("state", state));
nvps2.add(new BasicNameValuePair("key", key));
nvps2.add(new BasicNameValuePair("format", format));
httpPostGetCode.setEntity(new UrlEncodedFormEntity(nvps2));
CloseableHttpResponse respGetCode = httpClient.execute(httpPostGetCode);
try {
HttpEntity entityGetCode = respGetCode.getEntity();
out.println("respAuth------------>>" + respGetCode.toString());
// 最终目的 获取Location中的url中的某一值
Header location = respGetCode.getFirstHeader("Location");
out.println("location------------>>" + location.getValue());
EntityUtils.consume(entityGetCode);
} finally {
respGetCode.close();
}
} finally {
httpClient.close();
}
}
}