Try this:
String apiKey = "api:{key}"
String authHeader = "Basic " + Base64.encodeToString(apiKey.getBytes(), Base64.DEFAULT);
try {
String data = URLEncoder.encode("from", "UTF-8") + "=" + URLEncoder.encode("[email protected]", "UTF-8");
data += "&" + URLEncoder.encode("to", "UTF-8") + "=" + URLEncoder.encode("[email protected]", "UTF-8");
data += "&" + URLEncoder.encode("subject", "UTF-8") + "=" + URLEncoder.encode("subject", "UTF-8");
data += "&" + URLEncoder.encode("text", "UTF-8") + "=" + URLEncoder.encode("msg body", "UTF-8");
URL u = new URL("https://api.mailgun.net/{DOMAIN}/messages");
HttpURLConnection restConnection = (HttpURLConnection) u.openConnection();
restConnection.setRequestMethod("POST");
restConnection.setDoOutput(true);
restConnection.setRequestProperty("Authorization", authHeader);
OutputStreamWriter w = new OutputStreamWriter(restConnection.getOutputStream());
w.write(data);
w.flush();
w.close();
int status = restConnection.getResponseCode();
// switch statement to catch HTTP 200 and 201 errors
switch (status) {
case 200:
// live connection to your REST service is established here using getInputStream() method
BufferedReader br = new BufferedReader(new InputStreamReader(restConnection.getInputStream()));
// create a new string builder to store json data returned from the REST service
StringBuilder sb = new StringBuilder();
String line;
// loop through returned data line by line and append to stringbuilder 'sb' variable
while ((line = br.readLine()) != null) {
sb.append(line + "
");
}
br.close();
// remember, you are storing the json as a stringy
try {
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String containing data to Tweet activity (or whatever your activity is called!)
break;
case 400:
Log.d(TAG, "Bad request");
break;
case 401:
Log.d(TAG, "Unauthorized");
break;
case 402:
Log.d(TAG, "Request Failed");
break;
case 404:
Log.d(TAG, "404");
break;
case 500:
case 502:
case 503:
case 504:
Log.d(TAG, "Mailgun fail");
break;
}
} catch (Exception e) {
e.printStackTrace();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…