首页 > 解决方案 > 使用 httpconnection 发送 HTTP GET 请求失败

问题描述

我的请求失败了。这在邮递员中有效,但是在尝试 java 时,我尝试的每一种方式都失败了。下面的示例代码以及我得到的响应。我可以使用 httpsurlconnection 和 outputstreamwriter 成功地将 HTTPPost 发送到此 Web 服务,但是当尝试将其转换为 GET 时,没有任何不在 URL 本身中的内容,它会失败。非常感谢任何帮助!

//print out the encoded values
data.addToLog( “sha256hex: “, sha256hex);
data.addToLog( “xauth: “, xauth);
StringBuilder sb = new StringBuilder();
String baseurl = “https://” + apihost + endpoint + “?personID=” + personid;
data.addToLog( “BaseURL: “, baseurl);

//print out the JSON search request
try {
URL myurl = new URL(null, baseurl , new sun.net.www.protocol.https.Handler() );
HttpsURLConnection con = (HttpsURLConnection )myurl.openConnection();
con.setSSLSocketFactory(new TSLSocketConnectionFactory());
con.setRequestProperty(“X-Timestamp”, tsparam);
con.setRequestProperty(“X-Nonce”, nonce64);
con.setRequestProperty(“X-Authorization”, xauth);
con.setRequestProperty(“X-Test-Insecure”, “true”);
con.setRequestMethod(method);
con.setDoOutput(true);
con.setRequestProperty(“Content-Type”, “application/json;charset=utf-8”);

int responseCode = con.getResponseCode();
data.addToLog(“Response Code= “, con.getResponseCode() +”: “+ con.getResponseMessage());

if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

// print result
//System.out.println(response.toString());
data.addToLog(“Response:”, response.toString() );

}

日志结果:

PersonDetailsLookup,custom,Response Code= ,200: OK
PersonDetailsLookup,custom,Response:,{“serviceModel”:{“errorCode”:{“description”:”Unexpected System Error””value”:”500″}”errorMessage”:”API Invocation Failure – Unknown Error””severity”:{“description”:”FATAL””value”:”3″}}}

标签: gethttpconnection

解决方案


弄清楚了!它是内容类型,需要将其更改为文本而不是 json:

con.setRequestProperty(“内容类型”,“应用程序/文本;charset=utf-8”);


推荐阅读