private String readStream(InputStream postInputStream) { String jsonString = ""; BufferedReader postBufferedReader = new BufferedReader(new InputStreamReader(postInputStream), 10 * 1024); String postline = null; try { while ((postline = postBufferedReader.readLine()) != null) { DebugUtility.showLog(postline); jsonString = jsonString + postline; } postBufferedReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonString; }
/** * This is the main HTTREQUEST method * * @param apiurl the url of the called api * @param header header params * @param get get params (NOT USED) * @return the json object returned by the api */ public String httpRequest(String apiurl, HeaderParams header, PostParams post, boolean isPost) { // DEBUG DebugUtility.showLog(apiurl); URL url; try { String postParams = ""; if (post != null) { for (int i = 0; i < post.getKey().size(); i++) { if (i == 0) postParams = postParams + post.getKey().get(i) + "=" + URLEncoder.encode(post.getValue().get(i), "UTF-8"); else postParams = postParams + "&" + post.getKey().get(i) + "=" + URLEncoder.encode(post.getValue().get(i), "UTF-8"); } } url = new URL(apiurl); System.setProperty("http.keepAlive", "false"); postUrlConnection = (HttpsURLConnection) url.openConnection(); postUrlConnection.setUseCaches(false); postUrlConnection.setDoInput(true); header.getKey().add("X-BEINTOO-SDK-VERSION"); header.getValue().add(BeintooSdkParams.version); if (BeintooSdkParams.useSandbox) { header.getKey().add("sandbox"); header.getValue().add("true"); } for (int i = 0; i < header.getKey().size(); i++) { postUrlConnection.setRequestProperty(header.getKey().get(i), header.getValue().get(i)); } if (isPost) { postUrlConnection.setDoOutput(true); postUrlConnection.setRequestMethod("POST"); postUrlConnection.setRequestProperty( "Content-Length", "" + Integer.toString(postParams.getBytes().length)); DataOutputStream wr = new DataOutputStream(postUrlConnection.getOutputStream()); wr.writeBytes(postParams); wr.flush(); wr.close(); } else { postUrlConnection.setRequestMethod("GET"); } postInputStream = postUrlConnection.getInputStream(); jsonString = readStream(postInputStream); return jsonString; } catch (IOException e) { e.printStackTrace(); // IF THE SERVER RETURN ERROR THROW EXCEPTION try { if (postUrlConnection.getResponseCode() == 400) { InputStream postInputStream = postUrlConnection.getErrorStream(); jsonString = readStream(postInputStream); Message msg = new Gson().fromJson(jsonString, Message.class); throw new ApiCallException(msg.getMessage(), msg.getMessageID()); } DebugUtility.showLog("RESPONSE CODE " + postUrlConnection.getResponseCode()); } catch (IOException e1) { throw new ApiCallException(); } return "{\"messageID\":0,\"message\":\"ERROR\",\"kind\":\"message\"}"; } finally { if (postInputStream != null) try { postInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }