Skip to content

Instantly share code, notes, and snippets.

@mdamien
Last active February 6, 2022 22:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdamien/9273931 to your computer and use it in GitHub Desktop.
Save mdamien/9273931 to your computer and use it in GitHub Desktop.
Android POST request with Basic Auth
Log.d(TAG, "API CALL: POST "+url);
OutputStream output = null;
try {
String query = "furnail_name=hell&hi=2";//use URLEncode here
URLConnection connection = new URL("https://your-url.com/action/save").openConnection();
String authString = "Basic " + Base64.encodeToString((username + ":" + password).getBytes(),Base64.NO_WRAP);
connection.setRequestProperty("Authorization", authString);
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + "UTF-8");
output = connection.getOutputStream();
output.write(query.getBytes("UTF-8"));
InputStream response = connection.getInputStream();
Log.d(TAG,(IOUtils.toString(response)));
} catch (Exception e) {
e.printStackTrace();
} finally {
try { output.close(); } catch (Exception logOrIgnore) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment