MailGun Android HttpUrlConnection constant error 4

2019-09-14 01:20发布

问题:

After a complete and utter failure to implement code with Retrofit, I have used Android's HttpURLConnection class to try and send an email through MailGun. However whatever I seem to do I get error 400 bad request back. I do not know what I am doing wrong - similar code seems to be working perfectly within iOS. The 4 lines commented out make no difference. Hardcoding the values for from and to did not fix it either. I have tried using application/json for Content-Type as well. Any pointers in the right direction would be appreciated!

URL u = new URL("https://api.mailgun.net/v3/companyname.com/messages");
HttpURLConnection restConnection = (HttpURLConnection) u.openConnection();
restConnection.setRequestMethod("POST");
String authHeader = "Basic " + Base64.encodeToString(apiKey.getBytes(), Base64.DEFAULT);
restConnection.setRequestProperty("Authorization", authHeader);
restConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
restConnection.setRequestProperty("from", "Company Name <noreply@companyname.com>");
restConnection.setRequestProperty("to", "myemailaddress@gmail.com");
restConnection.setRequestProperty("subject", "test");
restConnection.setRequestProperty("text", "test");
//restConnection.setUseCaches(false);
//restConnection.setAllowUserInteraction(false);
//restConnection.setConnectTimeout(10000);
//restConnection.setReadTimeout(10000);
restConnection.connect();
int status = restConnection.getResponseCode();

回答1:

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("from@from.com", "UTF-8");
        data += "&" + URLEncoder.encode("to", "UTF-8") + "=" + URLEncoder.encode("to@to.com", "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 + "\n");
                }
                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();
    }


回答2:

If you want to use MailGun on Android just do few steps:

1) Check this library. And implement it.

2) This library is for Java, not for Android. So you need to add 'configurations' to your gradle file and it should look like this:

dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])
   compile 'net.sargue:mailgun:1.3.2'
}

configurations {
   compile.exclude group: 'javax.inject', module: 'javax.inject'
}

more information here

3) So now you can use this library: (don't forget to run it in background thread)

Configuration configuration = new Configuration()
    .domain("somedomain.com")
    .apiKey("key-xxxxxxxxxxxxxxxxxxxxxxxxx")
    .from("Test account", "postmaster@somedomain.com");
Response response = Mail.using(configuration)
    .to("marty@mcfly.com")
    .subject("This message has an text attachment")
    .text("Please find attached a file.")
    .multipart()
    .attachment(new File("/path/to/image.jpg"))
    .build()
    .send();