java http请求头设置强制服务端返回不同格式结果

本文演示了如何利用Apache HttpClient创建预配置支持集成Windows身份验证的客户端。通过具体代码实例,展示了如何发送HTTP GET请求并处理响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package org.apache.http.examples.client.win;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.WinHttpClients;

/**
 * This example demonstrates how to create HttpClient pre-configured with
 * support for integrated Windows authentication.
 */
public class ClientWinAuth {

    public final static void main(String[] args) throws Exception {

        if (!WinHttpClients.isWinAuthAvailable()) {
            System.out.println("Integrated Win auth is not supported!!!");
        }

        CloseableHttpClient httpclient = WinHttpClients.createDefault();
        // There is no need to provide user credentials
        // HttpClient will attempt to access current user security context through
        // Windows platform specific methods via JNI.
        try {
//            HttpGet httpget = new HttpGet("http://10.0.1.209:8084/WebServletTest/ServletTest");
            HttpGet httpget = new HttpGet("http://changba.com/s/rXjwse6PBuNQd4fROXSh_Q");
            httpget.addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36");
            System.out.println("Executing request " + httpget.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
//                System.out.println("----------------------------------------");
//                System.out.println(response.getStatusLine());
//                System.out.println(response.getProtocolVersion());
                HttpEntity httpEntity = response.getEntity();
                InputStream is = null;
                if (response.getEntity() != null) {
                    is = httpEntity.getContent();
                }
                String message = ConvertStreamToString(is);
                System.out.println("message=" + message);
//                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

    public static String ConvertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            System.out.println("Error=" + e.toString());
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                System.out.println("Error=" + e.toString());
            }
        }
        return sb.toString();
    }

}

 

### Java重定向时浏览器未正确跳转到新页面的原因分析 在Java Web开发中,如果使用`response.sendRedirect()`方法实现重定向功能却未能成功跳转至目标页面,通常可能是由以下几个方面引起: #### 1. **响应头已提交** 如果在调用`sendRedirect()`之前已经向客户端写入了任何数据(例如HTML内容或其他响应),则会抛出异常或导致行为不可预测。这是因为HTTP协议规定,在发送状态码和头部信息之后不能再修改它们[^1]。 ```java // 错误示例:先写出内容再尝试重定向 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("<html><body>Hello</body></html>"); response.sendRedirect("/newPage.jsp"); // 这里可能会失败 } ``` 为了避免这种情况发生,应确保所有的业务逻辑处理完毕后再决定是否执行重定向操作,并且在此之前不要输出任何内容到客户端。 --- #### 2. **路径设置错误** `sendRedirect()`中的参数可以是相对路径也可以是绝对路径。但是需要注意的是,相对路径是以当前站点根目录为基准的,而不是相对于当前请求URI。如果指定的目标URL有误,则可能导致无法找到对应的资源。 ```java String redirectUrl = "/correctPath/result.jsp"; // 正确的相对路径 response.sendRedirect(redirectUrl); ``` 另外还可以考虑采用上下文路径动态构建完整的URL来增强可移植性和减少硬编码风险: ```java String contextPath = request.getContextPath(); String fullRedirectUrl = contextPath + "/desiredResource"; response.sendRedirect(fullRedirectUrl); ``` --- #### 3. **缓存机制干扰** 浏览器可能因为某些配置而缓存之前的页面版本,即使服务器端发出了新的位置指令也可能被忽略掉。这尤其发生在测试阶段频繁刷新同一网页的情况下[^2]。 为了防止此类问题的发生,可以在每次重定向前清除潜在的影响因素: ```java response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "no-cache"); response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); response.sendRedirect(targetUrl); ``` 上述代码片段通过设定特定的HTTP header字段告知接收方不应存储此响应副本从而强制其每次都去获取最新版的信息源。 --- #### 4. **Session管理不当引发冲突** 尽管原引用提到ASP.NET环境下关于session保持的话题[^3],但在JSP/Servlet体系下同样存在类似的隐患——即跨域或者长时间闲置后再次访问期间由于缺乏有效的身份验证令牌致使服务端拒绝继续维持原有的对话关联关系进而造成预期之外的结果表现形式之一便是看似简单的跳转会变得复杂起来甚至完全失效。 针对这个问题的有效对策包括但不限于如下几种做法: - 确认每一次交互都携带必要的认证凭据; - 调整session超时期限以适应实际应用场景需求; - 利用cookie或者其他持久化技术辅助完成整个流程控制而不单纯依赖于内存驻留型的数据结构。 --- ### 综合解决方案总结 综上所述,要彻底解决Java程序运行过程中遇到的这种现象可以从以上几个角度逐一排查并采取相应措施加以改进优化直至恢复正常运作为止。 ```java protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ // 防止重复提交表单后的乱序显示问题 response.reset(); // 设置无缓存策略 response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "no-cache"); // 构造正确的跳转地址 String targetUrl = getServletContext().getContextPath()+"/targetPage.jsp"; // 执行重定向动作 response.sendRedirect(response.encodeRedirectURL(targetUrl)); }catch(IllegalStateException e){ System.err.println("Response already committed."); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值