使用httpconnection

时间:2019-02-22 18:52:57

标签: get httpconnection

我一直无法从请求中获取失败。这在邮递员中有效,但是在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″}}}

1 个答案:

答案 0 :(得分:0)

想通了!这是内容类型,需要将其更改为文本而不是json:

con.setRequestProperty(“ Content-Type”,“ application / text; charset = utf-8”);