NutzCN Logo
问答 httpclient能提交成功,为啥nutz的http客户端不能接收到正确的值
发布于 2006天前 作者 qq_2ac473ac 1742 次浏览 复制 上一个帖子 下一个帖子
标签:

httpclient的代码

		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		 JSONObject j=new JSONObject();
		 j.put("client_id", "XXXX");
	 	 j.put("client_secret", "XXXXXXX");
	 	StringEntity entity = new StringEntity(j.toString().trim(),"utf-8");//解决中文乱码问题   
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(entity);
		httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
		HttpEntity responseEntity=null;		
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			int status= response.getStatusLine().getStatusCode();
			System.out.println(EntityUtils.toString(response.getEntity()));
			if(status==302) {
	
				}

这个能得到正确的status302

JSONObject j=new JSONObject();
		j.put("client_secret","xxxx");
		j.put("client_id","xxxxx");
	 	 
		 Request req = Request.create(url, METHOD.POST);
		 req.setData(j.toString().trim());
				
		 org.nutz.http.Header header =req.getHeader();
		
		 header.set("Content-Type", "application/json;charset=utf-8");
		 System.out.println("header="+req.getHeader().get("Content-Type"));
		
		 Sender sender=Sender.create(req);
		 
		 Response response=sender.send();
		
		 System.out.println(response.getStatus());

这个不能的到正确status302

他们差别在哪儿啊

5 回复

默认会跟随重定向,sender有配置项

sender默认的就是跟随重定向,但是服务器返回的数据不对,需要重新验证。
但是htttclient手动跟随跳转,可以得到正确的值

try {
			response = httpClient.execute(httpPost);
			int code= response.getStatusLine().getStatusCode();
			System.out.println(EntityUtils.toString(response.getEntity()));
			if(code==302) {
				Header firsHeader = response.getFirstHeader("location");
				String newurl= firsHeader.getValue();
				HttpGet httpGet = new HttpGet(newurl);
				response = httpClient.execute(httpGet);
				responseEntity = response.getEntity();
				
			}
			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				//System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
				JSONObject js=new JSONObject(EntityUtils.toString(responseEntity));
				System.out.println("token="+js.get("code"));
			}

我又设置sender跟随跳转为false,然后手动跳转。

Sender sender=Sender.create(req);
		 sender.setFollowRedirects(false);
		 Response response=sender.send();
		
		 System.out.println(response.getStatus());
		 System.out.println(response.getContent());
		 org.nutz.http.Header resHeader=response.getHeader();
		 List<String> newurlString= resHeader.getValues("Location");
		 Response newrResponse=Http.get(newurlString.get(0));
		 System.out.println("jsonstring="+newrResponse.getContent());

服务器返回的还是不是正确的值,但是新的url拿到浏览器里面去都可以得到正确的返回。
这是啥原因啊,http.get和httpclient的get请求和浏览器地址的直接请求有啥不一样么

有cookie吧?

但是httpclient发起的get请求也没有带cookie啊。返回的location直接浏览器输入进去都能得到正确的答案

区别就是header咯, 完全模仿浏览器的header来发吧

添加回复
请先登陆
回到顶部