折腾:
【未解决】用Java实现百度模拟登陆
期间,先要去搞清楚如何实现,用Java的OkHttp库去抓取网络时,传递header等参数
okhttp header
好像:
.header(“Authorization”, userToken)
就可以了?
OKHttp设置Header的那些坑 | Glan Wang
http://glanwang.com/2017/06/21/Android/OKHttp设置Header的那些坑/
Accessing Headers Typically HTTP headers work like a Map<String, String>: each field has one value or none. But some headers permit multiple values, like Guava's Multimap. For example, it's legal and common for an HTTP response to supply multiple Vary headers. OkHttp's APIs attempt to make both cases comfortable. When writing request headers, use header(name, value) to set the only occurrence of name to value. If there are existing values, they will be removed before the new value is added. Use addHeader(name, value) to add a header without removing the headers already present. When reading response a header, use header(name) to return the last occurrence of the named value. Usually this is also the only occurrence! If no value is present, header(name) will return null. To read all of a field's values as a list, use headers(name). To visit all headers, use the Headers class which supports access by index. private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { Request request = new Request.Builder() .url("https://api.github.com/repos/square/okhttp/issues") .header("User-Agent", "OkHttp Headers.java") .addHeader("Accept", "application/json; q=0.5") .addHeader("Accept", "application/vnd.github.v3+json") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println("Server: " + response.header("Server")); System.out.println("Date: " + response.header("Date")); System.out.println("Vary: " + response.headers("Vary")); } }
【总结】
去试试用.header(key, value):
Request request = new Request.Builder() .url(url) .header("User-Agent", UserAgent_Mac_Chrome) .header("Host", "www.baidu.com") .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8") .header("Accept-Encoding", "gzip, deflate, br") .header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8") .header("Cache-Control", "no-cache") .build();
是可以获取正常返回的值的:
注:
关于所谓的interceptor,暂时用不到。等用到了再去研究,再去参考:
转载请注明:在路上 » 【已解决】Java中用OkHttp的请求传递header等参数