java httpclient 302_HttpClient如何解决302重定向问题

packagecom.btv;importorg.apache.http.Header;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.client.HttpClient;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.util.EntityUtils;/***@authorQiaoJiafei

*@version创建时间:2016年1月5日 上午10:17:46

* 类说明*/

public classTestLogin {public static voidmain(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) throwsException{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= newHttpPost(url);

httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

StringEntity se= newStringEntity(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= newHttpPost(newuri);

httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

se= newStringEntity(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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值