Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

MailGun Android HttpUrlConnection constant error 400

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 <[email protected]>");
restConnection.setRequestProperty("to", "[email protected]");
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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...