2017-01-14 3 views
0

После полного и полного отказа от реализации кода с помощью Retrofit я использовал класс HttpURLConnection для Android, чтобы попытаться отправить электронное письмо через MailGun. Однако, что бы я ни делал, я возвращаю ошибку 400 с ошибкой. Я не знаю, что я делаю неправильно - похоже, что код работает отлично в iOS. 4 строки, прокомментированные, не имеют никакого значения. Hardcoding значения для from и to также не исправляли его. Я также попытался использовать application/json для Content-Type. Любые указатели в правильном направлении были бы оценены!Постоянная ошибка MailGun Android HttpUrlConnection 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

Вы пробовали запрос отдельно от вашего кода? правильно ли оно вернулось? – Roljhon

+0

Вероятно, как вы определяете свой API, ошибка 400 означает, что ваши параметры запроса не могут быть поняты сервером – Roljhon

ответ

0

Попробуйте это:

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

Если вы хотите использовать MailGun на Android просто сделать несколько шагов:

1) Проверьте this library. И реализовать его.

2) Эта библиотека предназначена для Java, а не для Android. Таким образом, вы должны добавить «конфигурации» в свой Gradle файл и он должен выглядеть следующим образом:

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) Итак, теперь вы можете использовать эту библиотеку: (не забудьте запустить его в фоновая нить)

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(); 
Смежные вопросы