以下是我用curl做的事情:
curl -d "username=<user>&password=<pass>"/span> -X POST https://example.com/wp-json/api/v1/token
這就像一個魅力的作業,我正在接收令牌。 下面是curl發送的內容:
POST https://example.com/wp-json/api/v1/token HTTP/1.1
主機:example.com
用戶代理: curl/7.55.1。
接受。*/*
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[
][
]"
org.apache.http.wire - http-outgoing-0 >> "Content-Length: 45[
][
]"
org.apache.http.wire - http-outgoing-0 >> "Content-Type: application/x-www-form-urlencoded; charset=ISO-8859-1[
][
]"
org.apache.http.wire - http-outgoing-0 >> "主機:www.example.com[
][
]"
org.apache.http.wire - http-outgoing-0 >> "連接。Keep-Alive[
][
]"
org.apache.http.wire - http-outgoing-0 >> "用戶代理。Apache-HttpClient/4.5.13 (Java/1.8.0_121)[
][
]"
org.apache.http.wire - http-outgoing-0 >> "Accept-Encoding: gzip,deflate[
][
]"
org.apache.http.wire - http-outgoing-0 >> "[
][
]"
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"/span>, PlainConnectionSocketFactory.INSTANCE)
.register("https"/span>, 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中洗掉。 然而,它成功了!
uj5u.com熱心網友回復:
解決方案是驚人的簡單(和意想不到的):在我從URL中洗掉 "www "部分后,它開始作業!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/331036.html
標籤:
下一篇:如何處理相互沖突的同伴依賴關系?
