2017-01-14 8 views
0

Nach einem vollständigen und völligen Fehler bei der Implementierung von Code mit Retrofit, habe ich Android HttpURLConnection-Klasse verwendet, um zu versuchen, eine E-Mail über MailGun zu senden. Wie auch immer ich es zu tun scheint, bekomme ich 400 Fehler zurück. Ich weiß nicht, was ich falsch mache - ähnlicher Code scheint innerhalb von iOS perfekt zu funktionieren. Die 4 auskommentierten Zeilen machen keinen Unterschied. Das Hardcoding der Werte von from und to hat es auch nicht behoben. Ich habe versucht, Anwendung/Json für Content-Type auch zu verwenden. Irgendwelche Hinweise in die richtige Richtung würden geschätzt werden!MailGun Android HttpUrlConnection Konstante Fehler 400

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(); 
+0

haben Sie die Anfrage getrennt von Ihrem Code versucht? Ist es korrekt zurückgekehrt? – Roljhon

+0

ist es wahrscheinlich, wie Sie Ihre API definieren, Fehler 400 bedeutet, dass Ihre Anfrageparameter vom Server nicht verstanden werden können – Roljhon

Antwort

0

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 + "\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(); 
    } 
0

Wenn Sie nur tun wenige Schritte MailGun auf Android verwenden:

1) this library prüfen. Und implementieren Sie es.

2) Diese Bibliothek ist für Java, nicht für Android. Sie müssen also ‚Konfigurationen‘, um Ihre gradle Datei hinzufügen und es sollte wie folgt aussehen:

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, jetzt können Sie diese Bibliothek verwenden: (vergessen Sie nicht, es zu laufen in Hintergrund Thread)

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