- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试向网站发出 POST 请求。作为对 POST 请求的响应,我需要一些 JSON 数据。
使用 Apache 的 HttpClient 库,我可以毫无问题地执行此操作。响应数据是 JSON,所以我只是解析它。
package com.mydomain.myapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class MyApp {
private static String extract(String patternString, String target) {
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(target);
matcher.find();
return matcher.group(1);
}
private String getResponse(InputStream stream) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String inputLine;
StringBuffer responseStringBuffer = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responseStringBuffer.append(inputLine);
}
in.close();
return responseStringBuffer.toString();
}
private final static String BASE_URL = "https://www.volkswagen-car-net.com";
private final static String BASE_GUEST_URL = "/portal/en_GB/web/guest/home";
private void run() throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(BASE_URL + BASE_GUEST_URL);
CloseableHttpResponse getResponse = client.execute(httpGet);
HttpEntity responseEntity = getResponse.getEntity();
String data = getResponse(responseEntity.getContent());
EntityUtils.consume(responseEntity);
String csrf = extract("<meta name=\"_csrf\" content=\"(.*)\"/>", data);
System.out.println(csrf);
HttpPost post = new HttpPost(BASE_URL + "/portal/web/guest/home/-/csrftokenhandling/get-login-url");
post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
post.setHeader("User-Agent'", "Mozilla/5.0 (Linux; Android 6.0.1; D5803 Build/23.5.A.1.291; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.111 Mobile Safari/537.36");
post.setHeader("Referer", BASE_URL + "/portal");
post.setHeader("X-CSRF-Token", csrf);
CloseableHttpResponse postResponse = client.execute(post);
HttpEntity postResponseEntity = postResponse.getEntity();
String postData = getResponse(postResponseEntity.getContent());
System.out.println(postData);
EntityUtils.consume(postResponseEntity);
postResponse.close();
}
public static void main(String[] args) throws Exception {
MyApp myApp = new MyApp();
myApp.run();
}
}
但是我不能在我的项目中使用 HttpClient 库。我需要能够对“仅”HttpURLConnection 执行相同的操作。
但是 HttpClient 库有一些我无法理解的魔力。因为使用 HttpURLConnection 对我的 POST 请求的响应只是重定向到不同的网页。
有人能给我指出正确的方向吗?
这是我当前的 HttpURLConnection 尝试:
package com.mydomain.myapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyApp {
private static String extract(String patternString, String target) {
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(target);
matcher.find();
return matcher.group(1);
}
private final static String BASE_URL = "https://www.volkswagen-car-net.com";
private final static String BASE_GUEST_URL = "/portal/en_GB/web/guest/home";
private String getResponse(InputStream stream) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String inputLine;
StringBuffer responseStringBuffer = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responseStringBuffer.append(inputLine);
}
in.close();
return responseStringBuffer.toString();
}
private String getResponse(HttpURLConnection connection) throws Exception {
return getResponse(connection.getInputStream());
}
private void run() throws Exception {
HttpURLConnection getConnection1;
URL url = new URL(BASE_URL + BASE_GUEST_URL);
getConnection1 = (HttpURLConnection) url.openConnection();
getConnection1.setRequestMethod("GET");
if (getConnection1.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new Exception("Request failed");
}
String response = getResponse(getConnection1);
getConnection1.disconnect();
String csrf = extract("<meta name=\"_csrf\" content=\"(.*)\"/>", response);
System.out.println(csrf);
HttpURLConnection postRequest;
URL url2 = new URL(BASE_URL + "/portal/web/guest/home/-/csrftokenhandling/get-login-url");
postRequest = (HttpURLConnection) url2.openConnection();
postRequest.setDoOutput(true);
postRequest.setRequestMethod("POST");
postRequest.setInstanceFollowRedirects(false);
postRequest.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
postRequest.setRequestProperty("User-Agent'", "Mozilla/5.0 (Linux; Android 6.0.1; D5803 Build/23.5.A.1.291; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/63.0.3239.111 Mobile Safari/537.36");
postRequest.setRequestProperty("Referer", BASE_URL + "/portal");
postRequest.setRequestProperty("X-CSRF-Token", csrf);
postRequest.disconnect();
}
public static void main(String[] args) throws Exception {
MyApp myApp = new MyApp();
myApp.run();
}
}
最佳答案
感谢优秀的程序员资源,例如MKYong(你知道你之前访问过他的网站 ;-)),我会回顾一下它的要点以防 link永远下降。
要点:
The HttpURLConnection‘s follow redirect is just an indicator, in fact it won’t help you to do the “real” http redirection, you still need to handle it manually.
If a server is redirected from the original URL to another URL, the response code should be 301: Moved Permanently or 302: Temporary Redirect. And you can get the new redirected url by reading the “Location” header of the HTTP response header.For example, access to the normal HTTP twitter website – http://www.twitter.com , it will auto redirect to the HTTPS twitter website – https://www.twitter.com.
示例代码
package com.mkyong.http;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRedirectExample {
public static void main(String[] args) {
try {
String url = "http://www.twitter.com";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setReadTimeout(5000);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Request URL ... " + url);
boolean redirect = false;
// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
System.out.println("Response Code ... " + status);
if (redirect) {
// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
// open the new connnection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Redirect to URL : " + newUrl);
}
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();
System.out.println("URL Content... \n" + html.toString());
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
关于java - 如何使用 HttpURLConnection 以与 Apache HttpClient lib 相同的方式发出 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53091231/
我看到很多人发布关于 NullInjectorError: No provider for HttpClient! 的问题但是我在 Karma 单元测试中遇到了更具描述性的错误。我一直在学习 Angu
全部, 我创造: public static final HttpClient DEFAULT_HTTPCLIENT = HttpClients .createDefault(); f
我正在使用 HttpClient fluent api 编写验收测试,但遇到了一些麻烦。 @When("^I submit delivery address and delivery time$")
有人可以分享如何配置现代 HttpClient 4.5.3 以重试失败的请求并在每次重试前等待一段时间吗? 到目前为止,我似乎正确理解了 .setRetryHandler(new DefaultHtt
我在使用 java 中的 HttpClient 库时遇到问题。 目标网站在 SSL ( https://www.betcris.com ) 上,我可以从该网站加载索引页面就好了。 但是,显示不同运动赔
所以我的应用涉及大量网络调用(可能连接到 10 个不同的服务器)和获取数据。从我读过的几篇文章中,建议重用 HTTPClient 实例,因为它可以防止资源(套接字等)的浪费。但是我发现围绕可扩展且健壮
我正在调用一个外部 API,并希望我的 API 可以进行单元测试。为此,我正在尝试包装 HttpClient。我现在只需要一种方法。 这是我的界面。 public interface IHttpCli
出于调试目的,我希望看到将要发送的原始请求。有没有一种方法可以直接从 HttpPost 或 HttpClient 的API中获得没有HTTP监视器的信息? 我发现了一些“几乎”重复的问题,但不是针对这
我正在尝试在小型 WebAssemply 应用程序(使用 .NET 5 创建)中测试 HttpClient。program.cs 包含以下语句来添加 HttpClient 服务: builder.Se
我在 Application_Start 事件中创建了 HttpClient 的单个实例,以便在 Global.asax.cs 中的应用程序中重用 应用程序启动中的代码: protected
我对此有点新手...基本上我需要运行一个脚本来从谷歌趋势下载.csv 文件。我按照这个reference写了下面的代码,代码如下: HttpClient client = new Defau
我正在尝试实现一个基本的 1 spout - 1 bolt Storm 拓扑。我有一个 Storm Bolt,可以使用 Apache HttpClient (4.3.1) 发出 HTTP 请求。但是,
我正在尝试在我的 Xamarin.Forms 移动应用程序中使用 HttpClient 创建网络服务层。 没有单例模式 单例模式 在第一种方法中,我在每个新请求中创建新的 http 客户端对象通过移动
在下面的示例中,我创建了一个 Java 11 httpClient,然后创建了多个并发 HttpRequest。 这是不好的做法吗? 每个 HttpRequest 都应该有自己的 HttpClient
我正在开发一个 Drupal 8 自定义模块。我在任何节点类型中都有两个字段(url 和文本 html 字段)。这是该模块所期望的功能: 该模块将抓取“url字段”的页面并复制html代码以将它们粘贴
我正在为 httpclient 使用 apache httpcompnonents 库。我想在多线程应用程序中使用它,其中线程数会非常高,并且会有频繁的 http 调用。这是我用来在执行调用后读取响应
最近我将我的代码库从 .net core 1.0 迁移到 2.0 。之后,我随机收到错误 “使用 System.Net.Http.HttpClient 时服务器返回无效或无法识别的响应错误”。我在 1
我有该代码: while(!lastPage && currentPage < maxPageSize){ StringBuilder request = new Strin
我的应用程序使用 Apache HTTPClient 4.3.5 发送 HTTP 请求并获得响应。 我想弄清楚应用程序收到了什么响应。 以下是日志片段- [Jan 04 2015 05:38:14.1
如何从 HttpClient 类型的现有对象获取 cookie? 我正在使用 HttpClient 版本 4.3.3,它不再有方法 httpClient.getCookieStore() 了。 最佳答
我是一名优秀的程序员,十分优秀!