Android JSON Data Posting results in IO Exception Always - java

I have a server and I use following Link to post data in my DB
http://URL.php?action=insert&vhc=vehiclenumber&mobile=mobilenumberoftheperson&time=currenttime
To keep record of vehicle entering time, Now I want to post same Data from Android for which I am using Following Code:
Inside Button Goes this:
button.setOnClickListener(new View.OnClickListener() {
//Toast.makeText(getApplicationContext(),"Data is tried!", Toast.LENGTH_LONG).show();
public void onClick(View v)
{
new Thread(new Runnable() {
public void run() {
postData();
}
}).start();
}
});
And my PostData Function is defined below:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("url.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("vhc", "ABC124"));
nameValuePairs.add(new BasicNameValuePair("mobile", "089944440000"));
nameValuePairs.add(new BasicNameValuePair("time", "2014-12-28 22:22:52"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
message = e.getMessage();
// TODO Auto-generated catch block
} catch (IOException e) {
message= e.getMessage();
// TODO Auto-generated catch block
}
}
Now I tried to debug and found it failing at HttpResponse response = httpclient.execute(httppost); step and leads it to IOException, Please indicate my error to resolve the issue. Thanks!

In you current solution you create a thread, but the thread execute you code sequentially and it does not wait for the response from your server. As a result your client get a null response.
Solution : you have to use AsyncTask for retrieve/send data from/to server. Execute data retrieve part in the doBackground method of AsyncTask. And get your response from the postExecute method. See details here

Related

Uploading JSONObject to Iris CouchDb in Android

I´m currently working on an app and having my problems with uploading a JSONObject to my Iris CouchDb. But I can´t get it to work.
This is the code I´m using right now:
private class MyHttpPost extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... arg0)
{
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost("https://dbname.iriscouch.com/dbname");
try {
// Add your data
JSONObject jsonDoc = new JSONObject();
try {
jsonDoc.put("name", "test");
jsonDoc.put("autor", "test author");
jsonDoc.put("rundgangnr", "1");
jsonDoc.put("latitude", 58.0);
jsonDoc.put("longitude", 7.88);
} catch (JSONException e) {
e.printStackTrace();
} // end try
String body = jsonDoc.toString();
StringEntity entity = new StringEntity(body, "utf-8");
httpPost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
InputStream result = httpEntity.getContent();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return true;
}
}
In onCreate I do this to execute the function:
new MyHttpPost().execute();
When I run the app, there are no errors but nothing gets uploaded. So there isn´t any change in the database.
Am I using the wrong URL to upload it on Iris or is there something wrong with the code? I´m new to Android development and really would appreciate your help as I have been struggling with this for days now.
Perhaps you need to use https://accountname.iriscouch.com/dbname rather than https://dbname.iriscouch.com/dbname.
Also, if the request throws an IOException, your app will be silently swallowing the error so you might not be seeing it.

Turn a fatal crash into a non-fatal crashlytics report

The code in question:
final GenericAsyncTask task = new GenericAsyncTask();
task.background = new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(GCMIntentService.this.host);
String addremove = "add";
if(register == false) addremove = "remove";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("cmd", addremove));
nameValuePairs.add(new BasicNameValuePair("subscription_key", SUBSCRIPTION_KEY)); // unique per app
nameValuePairs.add(new BasicNameValuePair("token", str));
nameValuePairs.add(new BasicNameValuePair("os_family", "android"));
if(addremove.equals("remove")) nameValuePairs.add(new BasicNameValuePair("hard", "" + hard));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.setEntity(entity);
Log.i(LCHApplication.TAG, "Name Value Pairs: " + nameValuePairs.toString());
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
task.result = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
};
task.callback = new Runnable() {
public void run() {
Log.i(LCHApplication.TAG, "registration response: " + task.result.toString());
}
};
task.execute();
Which works great MOST of the time. Sometimes, however, task.result.toString(); is sometimes NULL which throws a java.lang.NullPointerException. I want to keep this crash because I want it to report in crashlytics so I can see how many people it's effecting. If I use a try/catch what can I throw to make sure it's a non-fatal crash instead? That way it will still report to crashlytics but it won't kill the app.
You don't have to throw any caught exception, you can log them very easily like this:
try {
myMethodThatThrows();
} catch (Exception e) {
Crashlytics.logException(e);
// handle your exception here!
}
Source: http://support.crashlytics.com/knowledgebase/articles/202805-logging-caught-exceptions

Put POST request with HttpRequest

I'm making a google login through GoogleTransport and ClientLogin.
private final GoogleTransport transport = new GoogleTransport();
private final ClientLogin authenticator = new ClientLogin();
Then I'm accessing the Picasa web api.
transport.setVersionHeader(PicasaWebAlbums.VERSION);
transport.applicationName = "google-picasaandroidsample-1.0";
HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE);
authenticator.authTokenType = PicasaWebAlbums.AUTH_TOKEN_TYPE;
authenticator.username = StaticVariables.USER_NAME+StaticVariables.USER_DOMAIN;
authenticator.password = StaticVariables.USER_PASSWORD;
try {
authenticator.authenticate().setAuthorizationHeader(transport);
HttpRequest request = transport.buildPostRequest();
request.setUrl("https://picasaweb.google.com/data/feed/api/user/default");
request.execute();
} catch (HttpResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The above is working fine.
Now I want to set a POST request. But buildPostRequest() method does not support any String parameter. So, unable to post any data at the URL. How to achieve it? Please help.
You may use HttpPost with NameValuePair
private boolean sendData(ArrayList<NameValuePair> data) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR_URL);
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Then create your Name Value pairs in a different method as
private ArrayList<NameValuePair> setupData() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
3);
nameValuePairs.add(new BasicNameValuePair(USERID, SAMPLE_USER_ID);
nameValuePairs.add(new BasicNameValuePair(USERNAME, SAMPLE_USER_NAME));
return nameValuePairs;
}
Atlast call the send data method in an AsyncTask or Intent service as sendData(setupdata())
Data in a post request is usually sent in the body of the request.

sending GCM message in java

I am new in Java programming. i have developed an android application which send a request to GCM server and in response its getting a registration id which i am send to my java server and on server i am storing it in database. Its working fine :)
For second part i have written http code in java server. with this code i am access the registration id from database and sending it to GCM server with a string message for for device. But i am getting error. my code for http client is here. please can some one help?
public static String REQUEST_URL = "https://android.googleapis.com/gcm/send";
private static String GCM_ID = "APA91bFEnZXT7YRTJm2d5NpbKcpJCuDwEIJjZmwYITIIWIOFIZHEtwYc8S3oN_Upe3RnSvUqcwmntIrMqaF8Vn04b_EZtvoDQMAqt21Zw9Sb9GhNXwVS70yDOjUyRohH7u1RmtTHRrkjaBUueIjS2gD1Uw1cQDJbQg";
/**
* #param args
*/
public static void main(String[] args) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("registration_id", GCM_ID));
formparams.add(new BasicNameValuePair("data", "this is data mesg"));
// UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
// "UTF-8");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(REQUEST_URL);
httpPost.setHeader("Authorization",
"key=AIzaSyBTgKVWevp0GwM5m2QAuF__39eEI0bclVA");
httpPost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
try {
httpPost.setEntity(new UrlEncodedFormEntity(formparams, "utf-8"));
httpclient.execute(httpPost);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I don't know what error you got, but this line :
formparams.add(new BasicNameValuePair("data", "this is data mesg"));
should be :
formparams.add(new BasicNameValuePair("data.message", "this is data mesg"));
Each payload parameter you include in the GCM message should have a name of the form data.<key>.

Sending simple POST by HttpRequest with Android

I want my application to send two strings through the query string to a php file that will handle them as POST variables.
So far I have this code
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("www.mywebsite.com/my_phpfile.php?var1=20&var2=31");
try {
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
I think it's an easy problem to solve but it's my first android app and I'd appreciate all the help.
Use nameValuePairs to pass data in the POST request.
Try it like this :
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/yourscript.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("string", "Hey"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// Catch Protocol Exception
} catch (IOException e) {
// Catch IOException
}
}

Categories