MailGun Android HttpUrlConnection constant error 400 - android

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

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

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

Related

Http post to server from Android app does not work

I have an Android app that sends a http post to a remote server:
protected Void doInBackground(Void... params) {
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MapsActivity.EXTRA_MESSAGE);
double longitude = intent.getDoubleExtra(MapsActivity.EXTRA_LONGITUDE, 0.0);
double latitude = intent.getDoubleExtra(MapsActivity.EXTRA_LATITUDE, 0.0);
Log.d("doInBackground", message);
Log.d("doInBackground", String.valueOf(longitude));
Log.d("doInBackground", String.valueOf(latitude));
URL url = null;
HttpURLConnection client = null;
try {
// Establish http connection
url = new URL("http://******.com/");
client = (HttpURLConnection) url.openConnection();
client.setDoOutput(true);
client.setDoInput(true);
client.setRequestMethod("POST");
client.connect();
OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());
String output;
output = URLEncoder.encode("message", "UTF-8")
+ "=" + URLEncoder.encode(message, "UTF-8");
output += "&" + URLEncoder.encode("longitude", "UTF-8") + "="
+ URLEncoder.encode(String.valueOf(longitude), "UTF-8");
output += "&" + URLEncoder.encode("latitude", "UTF-8") + "="
+ URLEncoder.encode(String.valueOf(latitude), "UTF-8");
Log.d("doInBackground(output)", output);
Log.d("doInBackground(code)", String.valueOf(client.getResponseCode())); // Return 200
writer.write(output);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.disconnect();
}
return null;
}
In the server, I have:
<?php
$m = urldecode($_POST['message']);
$long = urldecode($_POST['longitude']);
$lat = urldecode($_POST['latitude']);
print " ==== POST DATA =====
Message : $m
Longitude : $long
Latitude : $lat";
?>
client.getResponseCode() returns 200, I think that means my connection was successful? But the website still shows nothing. What might cause the problem?
I got
E/GMPM: getGoogleAppId failed with status: 10
E/GMPM: Uploading is not possible. App measurement disabled
might this be the problem?
What do you mean by the website doesn't show anything? You cannot see the print when you reload the web site because you are not saving it anywhere, you are simply printing out the values on that one single request. To debug you can write the post params to a file instead to see if they are coming through or better yet log the returned object on the android side.

How to fix "400 bad request" with uploading file on android with java HttpClient?

I need to upload a file to server. If i use the "curl -i -F filedata=#"PATH TO FILE" http://█.199.166.14/audiostream " it return a 200 OK code (Or may be this command incorrect) .
But when I use java function
public String send()
{
try {
url = "http://█.199.166.14/audiostream";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "test.pcm");
try {
Log.d("transmission", "started");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
ResponseHandler Rh = new BasicResponseHandler();
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
response.getEntity().getContentLength();
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 65728);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
catch (IOException e) { e.printStackTrace(); }
catch (Exception e) { e.printStackTrace(); }
Log.d("Response", sb.toString());
Log.d("Response", "StatusLine : " + response.getStatusLine() + " Entity: " + response.getEntity()+ " Locate: " + response.getLocale() + " " + Rh);
return sb.toString();
} catch (Exception e) {
// show error
Log.d ("Error", e.toString());
return e.toString();
}
}
catch (Exception e)
{
Log.d ("Error", e.toString());
return e.toString();
}
}
It's return 400 Bad request.
I'm also not sure that server proceed correctly my attempts to upload this file, but I can't check it.
From the error received its likely a bad formatted HTTP query. If audiostream is a php, write the full link.
Also it seems that there might be a wrong/bad encoded char at "http://█.199.166.14/audiostream, the link should be http://(IP or DNS)/(rest of URL)(the URI)
You should erase the link, then manually writte it again.
If those didnt fix the issue, its also possible that the Server (or its path equipment) might be blocking you. Check from the Access Log and the security rules of its accesses, that you are not blocked (some routers may block users from performing repeated querys as a sort of anti "Denial of Service" measure)

Android Compare Strings from HttpResponse

I'm having a curious problem, i have two apps (Web and Android), the first always response in text/plain with the following sintax
If the business logic is successfully the response is
OK
2013-04-01 14:31:26
if fail
ERROR
TypeError:MessageError
now the web app es working fine the problem is when i'm going to read the response in my android device
final HttpEntity entity = response.getEntity();
BufferedReader buffer;
String line = null;
try {
buffer = new BufferedReader(new InputStreamReader(entity.getContent()), 2048);
// Read first line
line = buffer.readLine();
Log.i(TAG, "Result : '" + line + "'");
if(line == "OK") {
// To something with the following lines
} else {
while(null != (line = buffer.readLine()) {
Log.i(TAG, "ERROR: " + line);
}
}
} catch (IllegalStateException e1) {
} catch (IOException e1) {
}
the problem line never is equals to OK event if the line Log.i(TAG, "Result : '" + line + "'") prints Result : 'OK'
In java you have to use .equals() to compare strings...
So your code should look like this:
if(line.equals("OK")) {

Handling HTTP Get/ Delete Android using REST

I m implementing a REST based HTTP server in Android. The server responds for GET, DELETE and POST requests. Two android devices communicate using HTTP Post (I m using a service, where a device keeps listening on a port and post to next device and this keeps going on).
I m testing the GET and DELETE using Mozilla Poster. Should I add a separate socket/port to handle the same? Because when I try now, sometimes I get timeout error or no response found. However, I am able to see server response in Logcat window. Please help me.
Code to handle GET request:
if(method.equals("GET"))
{
if(checkFileExisting())
{
BufferedReader reader = new BufferedReader(new FileReader(new File(getFilesDir()+File.separator+"script.json")));
String read;
StringBuilder builder = new StringBuilder("");
while((read = reader.readLine()) != null)
{
builder.append(read);
}
String JSONContents = builder.toString();
reader.close();
JSONObject jsonObject;
try {
jsonObject = new JSONObject(JSONContents);
String name = jsonObject.getString("name");
JSONObject stateObject = jsonObject.getJSONObject("state");
String stateValue = stateObject.getString("value");
if(name.equals(target))
{
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
response.setEntity(new StringEntity("State is:" + stateValue));
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
}
else
{
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
response.setEntity(new StringEntity("The requested resource " + target + " could not be found due to mismatch!!"));
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
response.setEntity(new StringEntity("The requested resource " + target + " could not be found!!"));
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
}
}
The link http://www.integratingstuff.com/2011/10/24/adding-a-webserver-to-an-android-app/ has a very good example. I missed conn.close() in my code.

Android connectivity with MySQL

I am developing a final year project where I need to connect Android emulator with MySQL database in order to retrieve values. Java file:
public class connectivity extends Activity {
/** Called when the activity is first created. */
TextView txt;
public static final String KEY_121 = "http://10.0.2.2/mysqlcon.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
// call the method to run the data retreival
txt.setText(getServerData(KEY_121));
}
private String getServerData(String returnString) {
InputStream is = null;
String result = null;
// the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1970"));
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
Log.i("log_tag", "id: " + json_data.getInt("id") + ", name: " + json_data.getString("name") + ", sex: " + json_data.getInt("sex") + ", birthyear: " + json_data.getInt("birthyear"));
// Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
I have also given an internet permission in my Android manifest file. But after running the application I get the following error in logcat:
ERROR PARSING DATA org.json.JSONException:A JSONArraytext must start with '[' at character 0
I think this goes to show that a null value is being returned. Please help me out as this is my final year project. I have spent hours trying to find the solutions but it has been of no use.
I am currently using Android 2.2. The wamp server is on the localhost so I am using the address 10.0.2.2 which is a special alias to localhost (127.0.0.1). Any help will be really appreciated.
Here is the PHP code:
<?php
mysql_connect("127.0.0.1","root","chetan");
mysql_select_db("db1");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output,JSON_FORCE_OBJECT));
mysql_close();
This is actually an issue I've run into before. The problem is your server isn't outputting valid JSON. It's missing some of the markup. I suggest you print the raw text of the response to Logcat and examine it. Perhaps even pass it into a JSON validator. That will also help you figure out if it is returning an empty value. If it's returning an empty value, then you'll need to debug your server...not your client...
Additionally, try visiting the php page from your browser and letting it simply display the JSON response. This will allow you to see what's being written by the server and help you determine where the problem really is. Just be aware, because the server is expecting a POST the easiest way to test this would probably to be to create a simple html form to POST the test data to that page. Without doing that, getting a browser to do a POST on it's own can be a pain.
do u need to use connection to php??? if not you can directly connect to mysql db to retrieve the result:
// Assume function to be :
public String customerData() {
String customerInfo = ""; //To store result
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection(
"jdbc:mysql://10.0.2.2:3306/retailer","root","pswrd");
PreparedStatement statement = con.prepareStatement("SELECT * FROM customers");
ResultSet result = statement.executeQuery();
while(result.next()) {
customerInfo = customerInfo + result.getString("name") + "&" +
result.getString("C_ID") + "&" + result.getString("address") +
"&" + result.getString("email");
// Here "&"s are added to the return string. This is help to split the
// string in Android application
}
} catch(Exception exc) {
System.out.println(exc.getMessage());
}
return customerInfo;
}
But to your project library include Connector jar file for Mysql.

Categories

Resources