精华内容
下载资源
问答
  • 在利用Java网络编程时,利用Java获取HTTP Request 和 Response字段;可以利用Java语言根据需要添加自定义的HTTP字段,而不必拘泥于标准HTTP定义的字段。代码如下:public class TestURL {public static void ...

    在利用Java网络编程时,利用Java获取HTTP Request 和 Response头字段;

    可以利用Java语言根据需要添加自定义的HTTP头字段,而不必拘泥于标准HTTP定义的头字段。

    代码如下:

    public class TestURL {

    public static void main(String[] args) {

    String destURLStr= "http://www.baidu.com";

    URL destURL = null;

    URLConnection urlCon = null;

    HttpURLConnection httpUrlCon= null;

    String readResFile = "C:/Users/zhoujw/Desktop/readResFile.html";

    BufferedWriter bw = null;

    try {

    bw = new BufferedWriter(new FileWriter(readResFile));

    destURL = new URL(destURLStr);

    urlCon = destURL.openConnection();

    httpUrlCon = (HttpURLConnection)urlCon;

    //set request property

    httpUrlCon.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");

    //可根据需要添加自定义请求头

    httpUrlCon.setRequestProperty("Test Header1", "test1");

    httpUrlCon.setRequestProperty("Test Header2", "test2");

    httpUrlCon.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader(httpUrlCon.getInputStream(), "gbk"));

    String webpage = null;

    while((( webpage = br.readLine()) != null))

    {

    //System.out.println(webpage);

    bw.write(webpage);

    bw.flush();

    }

    //debug

    System.out.println("Self Define Headers:");

    System.out.println(" Test Header1: " + httpUrlCon.getRequestProperty("Test Header1"));

    System.out.println(" Test Header2: " + httpUrlCon.getRequestProperty("Test Header2"));

    System.out.println();

    //echo request property

    echoRequestHeaders(httpUrlCon);

    //echo response property

    echoResponseHeaders(httpUrlCon);

    } catch (MalformedURLException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    public static void echoRequestHeaders(HttpURLConnection httpUrlCon){

    System.out.println("Request Headers:");

    System.out.println(" " + httpUrlCon.getRequestMethod() + " / " + " HTTP/1.1");

    System.out.println(" Host: " + httpUrlCon.getRequestProperty("Host"));

    System.out.println(" Connection: " + httpUrlCon.getRequestProperty("Connection"));

    System.out.println(" Accept: " + httpUrlCon.getRequestProperty("Accept"));

    System.out.println(" User-Agent: " + httpUrlCon.getRequestProperty("User-Agent"));

    System.out.println(" Accept-Encoding: " + httpUrlCon.getRequestProperty("Accept-Encoding"));

    System.out.println(" Accept-Language: " + httpUrlCon.getRequestProperty("Accept-Language"));

    System.out.println(" Cookie: " + httpUrlCon.getRequestProperty("Cookie"));

    System.out.println(" Connection: " + httpUrlCon.getHeaderField("Connection"));//利用另一种读取HTTP头字段

    System.out.println();

    }

    public static void echoResponseHeaders(HttpURLConnection httpUrlCon) throws IOException{

    System.out.println("Response Headers:");

    System.out.println(" " + "HTTP/1.1 " + httpUrlCon.getResponseCode() + " " + httpUrlCon.getResponseMessage());

    System.out.println(" status: " + httpUrlCon.getResponseCode() + " " + httpUrlCon.getResponseMessage());

    System.out.println(" content-encoding: " + httpUrlCon.getContentEncoding());

    System.out.println(" content-length : " + httpUrlCon.getContentLength());

    System.out.println(" content-type: " + httpUrlCon.getContentType());

    System.out.println(" Date: " + httpUrlCon.getDate());

    System.out.println(" ConnectTimeout: " + httpUrlCon.getConnectTimeout());

    System.out.println(" expires: " + httpUrlCon.getExpiration());

    System.out.println(" content-type: " + httpUrlCon.getHeaderField("content-type"));//利用另一种读取HTTP头字段

    System.out.println();

    }

    }运行结果:

    Self Define Headers:

    Test Header1: test1

    Test Header2: test2

    Request Headers:

    GET / HTTP/1.1

    Host: www.baidu.com

    Connection: keep-alive

    Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2

    User-Agent: Java/1.6.0_20

    Accept-Encoding: gzip,deflate,sdch

    Accept-Language: null

    Cookie: null

    Connection: Keep-Alive

    http://www.baidu.com

    Response Headers:

    HTTP/1.1 200 OK

    status: 200 OK

    content-encoding: gzip

    content-length : -1

    content-type: text/html; charset=utf-8

    Date: 1427817028000

    ConnectTimeout: 0

    expires: 1427817001000

    content-type: text/html; charset=utf-8

    原文:http://blog.csdn.net/tterminator/article/details/44789667

    展开全文
  • JAVA如何获取HTTP请求头在利用Java网络编程时,常常需要获取HTTP请求头,那么JAVA如何获取HTTP请求头呢?下面小编为大家介绍了JAVA获取HTTP请求头的.方法,希望能帮到大家!在利用Java网络编程时,利用Java获取...

    JAVA如何获取HTTP请求头

    在利用Java网络编程时,常常需要获取HTTP请求头,那么JAVA如何获取HTTP请求头呢?下面小编为大家介绍了JAVA获取HTTP请求头的.方法,希望能帮到大家!

    在利用Java网络编程时,利用Java获取HTTP Request 和 Response头字段,可以利用Java语言根据需要添加自定义的HTTP头字段,而不必拘泥于标准HTTP定义的头字段。

    代码如下:

    public class TestURL {

    public static void main(String[] args) {

    String destURLStr= "http://www.baidu.com";

    URL destURL = null;

    URLConnection urlCon = null;

    HttpURLConnection httpUrlCon= null;

    String readResFile = "C:/Users/zhoujw/Desktop/readResFile.html";

    BufferedWriter bw = null;

    try {

    bw = new BufferedWriter(new FileWriter(readResFile));

    destURL = new URL(destURLStr);

    urlCon = destURL.openConnection();

    httpUrlCon = (HttpURLConnection)urlCon;

    //set request property

    httpUrlCon.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");

    //可根据需要添加自定义请求头

    httpUrlCon.setRequestProperty("Test Header1", "test1");

    httpUrlCon.setRequestProperty("Test Header2", "test2");

    httpUrlCon.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader(httpUrlCon.getInputStream(), "gbk"));

    String webpage = null;

    while((( webpage = br.readLine()) != null))

    {

    //    System.out.println(webpage);

    bw.write(webpage);

    bw.flush();

    }

    //debug

    System.out.println("Self Define Headers:");

    System.out.println(" Test Header1: " + httpUrlCon.getRequestProperty("Test Header1"));

    System.out.println(" Test Header2: " + httpUrlCon.getRequestProperty("Test Header2"));

    System.out.println();

    //echo request property

    echoRequestHeaders(httpUrlCon);

    //echo response property

    echoResponseHeaders(httpUrlCon);

    } catch (MalformedURLException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    public static void echoRequestHeaders(HttpURLConnection httpUrlCon){

    System.out.println("Request Headers:");

    System.out.println(" " + httpUrlCon.getRequestMethod() + " / " + " HTTP/1.1");

    System.out.println(" Host: " + httpUrlCon.getRequestProperty("Host"));

    System.out.println(" Connection: " + httpUrlCon.getRequestProperty("Connection"));

    System.out.println(" Accept: " + httpUrlCon.getRequestProperty("Accept"));

    System.out.println(" User-Agent: " + httpUrlCon.getRequestProperty("User-Agent"));

    System.out.println(" Accept-Encoding: " + httpUrlCon.getRequestProperty("Accept-Encoding"));

    System.out.println(" Accept-Language: " + httpUrlCon.getRequestProperty("Accept-Language"));

    System.out.println(" Cookie: " + httpUrlCon.getRequestProperty("Cookie"));

    System.out.println(" Connection: " + httpUrlCon.getHeaderField("Connection"));//利用另一种读取HTTP头字段

    System.out.println();

    }

    public static void echoResponseHeaders(HttpURLConnection httpUrlCon) throws IOException{

    System.out.println("Response Headers:");

    System.out.println(" " + "HTTP/1.1 " + httpUrlCon.getResponseCode() + " " + httpUrlCon.getResponseMessage());

    System.out.println(" status: " + httpUrlCon.getResponseCode() + " " + httpUrlCon.getResponseMessage());

    System.out.println(" content-encoding: " + httpUrlCon.getContentEncoding());

    System.out.println(" content-length : " + httpUrlCon.getContentLength());

    System.out.println(" content-type: " + httpUrlCon.getContentType());

    System.out.println(" Date: " + httpUrlCon.getDate());

    System.out.println(" ConnectTimeout: " + httpUrlCon.getConnectTimeout());

    System.out.println(" expires: " + httpUrlCon.getExpiration());

    System.out.println(" content-type: " + httpUrlCon.getHeaderField("content-type"));//利用另一种读取HTTP头字段

    System.out.println();

    }

    }

    运行结果:

    Self Define Headers:

    Test Header1: test1

    Test Header2: test2

    Request Headers:

    GET / HTTP/1.1

    Host: www.baidu.com

    Connection: keep-alive

    Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2

    User-Agent: Java/1.6.0_20

    Accept-Encoding: gzip,deflate,sdch

    Accept-Language: null

    Cookie: null

    Connection: Keep-Alive

    http://www.baidu.com

    Response Headers:

    HTTP/1.1 200 OK

    status: 200 OK

    content-encoding: gzip

    content-length : -1

    content-type: text/html; charset=utf-8

    Date: 1427817028000

    ConnectTimeout: 0

    expires: 1427817001000

    content-type: text/html; charset=utf-8

    【JAVA如何获取HTTP请求头】相关文章:

    展开全文
  • 获取方式一InputStream in = request.getInputStream();int len = 0;byte buffer[] = new byte[1024];while((len = in.read(buffer)) > 0) {System.out.println(len);System.out.println(new String(buffer,0,len...

    获取方式一

    InputStream in = request.getInputStream();

    int len = 0;

    byte buffer[] = new byte[1024];

    while((len = in.read(buffer)) > 0) {

    System.out.println(len);

    System.out.println(new String(buffer,0,len));

    }

    获取方式二

    String value  = request.getParameter("username");

    if(value != null && !value.trim().equals("")){

    System.out.println(value);

    }

    获取方式三

    Enumeration e = request.getParameterNames();

    while(e.hasMoreElements()){

    String name = (String)e.nextElement();

    value = request.getParameter(name);

    System.out.println(name + ":" + value);

    }

    获取方式四

    String[] values = request.getParameterValues("username");

    for(int i=0;values !=null && i < values.length;i++){

    System.out.println(values[i]);

    }

    获取方式五

    Map map = request.getParameterMap();

    User user = new User();

    BeanUtils.populate(user, map);

    ... 这里引用了 commons-beanutils-1.8.0.jar 和 commons-logging.jar 包

    public class User{

    public string[] getUsername(){...}

    public string[] getPassword(){...}

    }

    展开全文
  • 业务中遇到了一些场景,需要对请求做统一拦截,用请求参数计算新的变量设置到请求头中。以下分别用Filter和Interceptor两种方式实现,(建议使用Filter的方法,因为Interceptor的方法仅仅对Post和GET方法有效,并不...

    业务中遇到了一些场景,需要对请求做统一拦截,用请求参数计算新的变量设置到请求头中。

    以下分别用Filter和Interceptor两种方式实现,(建议使用Filter的方法,因为Interceptor的方法仅仅对Post和GET方法有效,并不支持PUT等其他方法,主要原因是因为HttpServletRequest接口的实现类不同,以下仅支持了POST和GET方法)

    场景:

    我们有两类用户,一类用户的请求中头部header中有用户名字参数(userName),另一类用户的请求并无请求header,但是请求参数requestParam中有userId参数,我们可以通过userId查库等计算出userName。

    需求:

    我们想统一两类用户,使请求达到我们的controller层的时候头部统一都有userName。

    具体:

    以下的两种方式实现了这个需求,controller层获取userName,将优先使用从requestParam中的userId计算出来的userName。

    1、Filter实现

    package com.paomo.filter;

    import org.springframework.context.annotation.Configuration;

    import javax.servlet.*;

    import javax.servlet.annotation.WebFilter;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletRequestWrapper;

    import java.io.IOException;

    import java.util.*;

    @Configuration

    @WebFilter(value = "/*")

    public class ParamFilter implements Filter {

    private static final String USER_PARAM = "userId";

    private static final String USER_HEADER = "userName";

    @Override

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;

    HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(req);

    String userId = request.getParameter(USER_PARAM);

    //依据你自己的业务通过userId获取userName

    String userName = getUserNameById(userId);

    requestWrapper.addHeader(USER_HEADER, userName);

    chain.doFilter(requestWrapper, response);

    }

    @Override

    public void destroy() {

    }

    public class HeaderMapRequestWrapper extends HttpServletRequestWrapper {

    public HeaderMapRequestWrapper(HttpServletRequest request) {

    super(request);

    }

    private MapheaderMap = new HashMap();

    public void addHeader(String name, String value) {

    headerMap.put(name, value);

    }

    @Override

    public String getHeader(String name) {

    String headerValue = super.getHeader(name);

    if (headerMap.containsKey(name)) {

    headerValue = headerMap.get(name);

    }

    return headerValue;

    }

    @Override

    public EnumerationgetHeaderNames() {

    Listnames = Collections.list(super.getHeaderNames());

    for (String name : headerMap.keySet()) {

    names.add(name);

    }

    return Collections.enumeration(names);

    }

    @Override

    public EnumerationgetHeaders(String name) {

    Listvalues = Collections.list(super.getHeaders(name));

    if (headerMap.containsKey(name)) {

    values.add(headerMap.get(name));

    }

    return Collections.enumeration(values);

    }

    }

    }

    2、Interceptor实现

    @Component

    public class ParamInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(ParamInterceptor.class);

    private static final String USER_PARAM = "userId";

    private static final String USER_HEADER = "userName";

    @Override

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    if (handler instanceof HandlerMethod) {

    String userId = request.getParameter(USER_PARAM);

    if (StringUtils.isNotBlank(userId)) {

    //依据你自己的业务通过userId获取userName

    String userName = getUserNameById(userId);

    reflectSetHeader(request, USER_HEADER, userName);

    }

    }

    return true;

    }

    @Override

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    super.postHandle(request, response, handler, modelAndView);

    }

    @Override

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    super.afterCompletion(request, response, handler, ex);

    }

    private void reflectSetHeader(HttpServletRequest request, String key, String value){

    Class extends HttpServletRequest> requestClass = request.getClass();

    logger.info("request实现类={}", requestClass.getName());

    try {

    Field request1 = requestClass.getDeclaredField("request");

    request1.setAccessible(true);

    Object o = request1.get(request);

    Field coyoteRequest = o.getClass().getDeclaredField("coyoteRequest");

    coyoteRequest.setAccessible(true);

    Object o1 = coyoteRequest.get(o);

    Field headers = o1.getClass().getDeclaredField("headers");

    headers.setAccessible(true);

    MimeHeaders o2 = (MimeHeaders)headers.get(o1);

    o2.removeHeader(key);

    o2.addValue(key).setString(value);

    } catch (Exception e) {

    logger.info("reflect set header error {}", e);

    }

    }

    }

    展开全文
  • //json格式的请求数据封装 JSONObject param= newJSONObject(); param.put("bidId","1027228"); param.put("datumId","102"); param.put("enclosure",enclosure.toString()); System.out.println(param.toString())...
  • } } 修改swagger的配置文件如上即能满足swagger中所有的接口默认都加上ticket参数,非必填如下图: 以上这篇java swagger ui 添加header请求头参数的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也...
  • <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> Insert title here 登录测试 登录名: 密码:
  • import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; @RestController public class TestController { /** ...
  • HTTP协议不对URI的长度作事先的限制,服务器必须能够处理任何他们提供资源的URI,并且应该能够处理无限长度的URIs,这种无效长度的URL可能会在客户端以基于GET方式的请求时产生。如果服务器不能处理太长的URI的时候...
  • HTTP请求头1)请求(客户端->服务端[request])GET(请求的方式) /books/java.html(请求的目标资源) HTTP/1.1(请求采用的协议和版本号)Accept: */*(客户端能接收的资源类型)Accept-Language: en-us(客户端接收的语言...
  • 1首先把json参数设置好JSONObject json1=new JSONObject();json1.put("Bandwidth","");json1.put("circuitType","");json1.put("portid","");json1.put("circuitno","...2设置header请求头和url以及参数public stat...
  • String headValue = request.getHeader("user-agent");Enumeration en = request.getHeaders("Accept-Encoding");while(en.hasMoreElements()){headValue = (String) en.nextElement();String value = request.getHe...
  • importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.URL;importjava.net.URLConnection;importjava.util.List;imp...
  • 声明:1.User-Agent是可以伪造的2.User-Agent中含有操作系统和版本信息3.在看见几位的博客,感觉不是很完善,刚好项目上用到,引用几位兄弟的博客,自己进一步完善。...import nl.bitwalker.useragentutils.Browser;...
  • java模拟Http Post请求带参数请求头

    千次阅读 2021-03-05 11:49:50
    //添加请求头参数 //post.addHeader("timestamp","1594695607545"); CloseableHttpClient client = HttpClients.createDefault(); //启动执行请求,并获得返回值 CloseableHttpResponse response = client....
  • java获取前端请求字段的方法package test.request;import java.io.IOException;import java.io.InputStream;import java.lang.reflect.InvocationTargetException;import java.util.Enumeration;import java.util....
  • 一定要有一个空行,表示请求头结束,否则,服务端无法判断请求头是否结束,从而挂掉另外需要特别注意的是Content-Length后的数据长度值一定要正确,是获取的数据体部分的字节长度,具体就是 userid=aaaaaaa&password...
  • 下面以 Java 为例实现该逻辑: public static boolean isAndroid(String ua) { return ua.contains("linux") || ua.contains("android") || ua.contains("adr") || ua.contains("okhttp"); } public static boolean...
  • 场景:过滤器中获取参数Token并添加到请求头(用户认证兼容老系统)请求头和请求参数是不能直接修改,也没有提供修改的方法,但是可以在过滤器和拦截器中使用HttpServletRequestWrapper包装类达到修改的目的。...
  • 对于第一种直接在浏览器地址中输入URL地址的情况,浏览器不会发送Referer请求头,而对于第二种情况,浏览器会使用Referer头字段标识发出请求的超链接所在的网页的URL。例如,本地Tomcat服务器的chapter03项目中有一...
  • } /** * post form * * @param host https://ip:port/ * @param path 接口路径 * @param headers 请求头 * @param querys 添加到请求路径上的参数 * @param bodys 请求体 * @return * @throws Exception */ public ...
  • 当我们feign调用提供者需要携带自定义的请求头,或者想继续传递上游服务的请求头信息时,可进行如下方式处理 实现RequestInterceptor,并Configuration注解标记为配置类 复写apply 方法,将我们的自定义的请求头 ...
  • 我有一些代码,这意味着通过HTTP向服务器发送GET请求,...并没有:Java HTTP GET请求给出403 Forbidden,但在浏览器中工作private static String fetch() throws UnsupportedEncodingException, MalformedURLExcepti...
  • Java 请求对象详解

    千次阅读 2021-06-13 15:59:26
    文章目录2 请求对象2.1 请求对象概述2.1.1 关于请求2.1.2 常用请求对象2.2 常用方法介绍2.3 请求对象的使用示例2.3.1 请求对象常用方法1-获取各种路径2.3.2 请求对象常用方法2-获取请求头信息2.3.3 请求对象常用方法...
  • Get 请求获取 Token 示例 HttpHeaders header = new HttpHeaders(); JSONObject jsonObj = HttpHelper.sendGetRequest(url, header); String token = jsonObj.getString("token"); Post 请求获取数据示例 ...
  • 1 packagecom.zhl.common.utils;23 importorg.jsoup.Connection;4 importorg.jsoup.Connection.Method;5 importorg.jsoup.Connection.Response;6 importorg.jsoup.Jsoup;78 import javax.net.ssl...9 import java.io...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,608,733
精华内容 643,493
关键字:

java请求头

java 订阅