public String postData( PasswordAuthentication credentials, String urlString, String contentType, String accept, String data) throws Exception { Log.i(TAG, "Calling url: " + urlString); HttpURLConnection connection; URL url; try { url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); if (!TextUtils.isEmpty(contentType)) { connection.setRequestProperty("Content-Type", contentType); } if (!TextUtils.isEmpty(accept)) { connection.setRequestProperty("Accept", accept); } addGlobalHeaders(connection); connection.connect(); if (connection == null) { return null; } byte[] dataBytes = data.getBytes("UTF-8"); DataOutputStream os = new DataOutputStream(connection.getOutputStream()); os.write(dataBytes); os.flush(); os.close(); BufferedReader br = null; if (connection.getResponseCode() == 200) { InputStream inputStream = connection.getInputStream(); br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); } StringBuilder sb = new StringBuilder(); try { String line; if (br != null) { while ((line = br.readLine()) != null) { sb.append(line); } } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } Log.i(TAG, "Response: " + sb.toString()); return sb.toString(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } Log.e(TAG, "Http call failed"); return null; }
public String getResponse( PasswordAuthentication credentials, String urlString, String contentType, String accept) { Log.i(TAG, "Calling url: " + urlString); HttpURLConnection connection = null; URL url; try { url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setDoInput(true); if (!TextUtils.isEmpty(contentType)) { connection.setRequestProperty("Content-Type", contentType); } if (!TextUtils.isEmpty(accept)) { connection.setRequestProperty("Accept", accept); } addGlobalHeaders(connection); connection.connect(); if (connection == null) { return null; } BufferedReader br = null; if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); } else { Log.i(TAG, "Response code for getResponse is :" + connection.getResponseCode()); } StringBuilder sb = new StringBuilder(); try { String line; if (br != null) { while ((line = br.readLine()) != null) { sb.append(line); } } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } catch (ConnectException e) { Log.i(TAG, "failed to connect Internet is not working"); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } return null; }