获取JWS令牌与curl一起工作,但与Java无关



我是这样设置curl的:

curl -d "username=<user>&password=<pass>" -X POST https://example.com/wp-json/api/v1/token

这工作像一个魅力,我正在接收令牌。下面是curl发送的内容:

POST https://example.com/wp-json/api/v1/token HTTP/1.1
Host: example.com
User-Agent: curl/7.55.1
Accept: */*
Content-Length: <length>
Content-Type: application/x-www-form-urlencoded
username=<user>&password=<pass>

使用Java,我收到代码403。以下是HttpClient的调试输出:

org.apache.http.wire - http-outgoing-0 >> "POST /wp-json/api/v1/token HTTP/1.1[r][n]"
org.apache.http.wire - http-outgoing-0 >> "Content-Length: 45[r][n]"
org.apache.http.wire - http-outgoing-0 >> "Content-Type: application/x-www-form-urlencoded; charset=ISO-8859-1[r][n]"
org.apache.http.wire - http-outgoing-0 >> "Host: www.example.com[r][n]"
org.apache.http.wire - http-outgoing-0 >> "Connection: Keep-Alive[r][n]"
org.apache.http.wire - http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5.13 (Java/1.8.0_121)[r][n]"
org.apache.http.wire - http-outgoing-0 >> "Accept-Encoding: gzip,deflate[r][n]"
org.apache.http.wire - http-outgoing-0 >> "[r][n]"
org.apache.http.wire - http-outgoing-0 >> "username=<user>&password=<pass>"

我看不出curl和java有什么明显的区别。谁知道我做错了什么?

下面是我当前的java代码:

public void getToken(URI url, String username, String password) {
HttpEntity entity = new StringEntity("username=" + username + "&password=" + password, ContentType.APPLICATION_FORM_URLENCODED);
HttpHost target = new HttpHost(url.getHost(), 443, "https");
SSLContext sslcontext = SSLContexts.createSystemDefault();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslcontext, new String[] { "TLSv1.2", "SSLv3" }, null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", sslConnectionSocketFactory)
.build();
PoolingHttpClientConnectionManager cm = new 
PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslConnectionSocketFactory)
.setConnectionManager(cm)
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
int statusCode = 0;
try (CloseableHttpResponse httpResponse = httpClient.execute(target, httpPost)) {
statusCode = httpResponse.getStatusLine().getStatusCode();
//parse response here
}
}

解决方法很简单:我的一个朋友告诉我,我应该删除"www"从url。然而,它成功了!

解决方案非常简单(而且出乎意料):在我删除了"部分从URL开始工作!!

相关内容

最新更新