我想使用HttpClient将以下PHP代码转换为Java:
$request = curl_init('URL');
curl_setopt_array($request, [
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
],
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => '{"req": {"Data": "KEY", "DataType": 1}}',
CURLOPT_REFERER => 'REFERER URL'
]);
$response = curl_exec($request);
curl_close($request);
我有的java代码:
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("URL");
String json = "{\"req\": {\"Data\": \"KEY\", \"DataType\": 1}}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Referer", "REFERER URL");
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
System.out.println(EntityUtils.toString(responseEntity));
client.close();
出于某种原因,PHP返回{"d": "the data i want"}
,而java返回{"d": null}
。
我知道这不是因为内容类型,因为故意在PHP中将其改为废话会使curl返回一个html页面,而不是{“d”:null}。
当我没有设置PHP中的referer时,我得到了{"d": null}
,但当它被设置为任何url我希望它工作。
当POSTFIELDS中的“Data”设置为错误的键时,我{"d": null}
也会得到。
发布于 2018-08-31 13:08:19
这条线对我来说最可疑:
HttpPost httpPost = new HttpPost("URL");
您将字符串“URL”作为URL放置,当然这不是有效的URL。所以我会尝试在那里输入一个有效的URL并再试一次。
同样在这一行上尝试添加有效的URL:
httpPost.addHeader("Referer", "REFERER URL");
此处“REFERER URL”也不是有效的URL。
https://stackoverflow.com/questions/-100002525
复制相似问题