Search code examples
gethttpconnection

failure sending HTTP GET request using httpconnection


I am stuck getting a failure back from my request. This works in postman but when trying in java, it fails every way I try it. Sample code below along with the response I get. I am able to send an HTTPPost to this webservice successfully using httpsurlconnection and outputstreamwriter but when trying to convert this to a GET without any that are not in the URL itself, it fails. Any help is very appreciated!!

//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() );

}

Log results:

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″}}}

Solution

  • Figured it out! It was the content type and it needed to be changed to text instead of json:

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