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.
Related
I am trying to get an XML document from URL. I know I should not do this on the UI thread, so I start a new one:
Thread t = new Thread(new GetXML());
t.start();
This starts the inner class GetXML which implements Runnable.
private class GetXML implements Runnable {
#Override
public void run() {
String xmlString = getXmlFromUrl(<URL of the XML as String>);
Document xmlDoc = getDomElement(xmlString);
String textValue = getTextValue(pointWhereItBreaks, xmlDoc, "movie");
}
}
As you can see, this executes a few methods, but the problem is already in the first one getXmlFromUrl:
public String getXmlFromUrl(String xmlUrl) {
String xmlString = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(xmlUrl);
//the following line causes the problem
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xmlString = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xmlString;
}
I have located the line where it breaks. It doesn't pass the following line:
HttpEntity httpEntity = httpResponse.getEntity();
Does anybody can tell me how to fix the code? I am stuck at this problem for days. I am able to get XML documents by a URL when I run a java application from my computer with a similar code. Why does it not work with Android?
Thank you very much!
I am fairly confident this code works (I used it in another part of my project for a different API) as far as posting but I do not think the URL is being formatted correctly. I want to know if there is anyway to view the full URL after building all of the entities so I can see if the final URL is formatted correctly. Code:
My URL = http://pillbox.nlm.nih.gov/PHP/pillboxAPIService.php
Method = POST
API key = not going to post (works though)
drugName = just a string that has the name of a drug
I have logs in the code to try and view the url but they aren't returning anything close and the debugger isn't either.
I am trying to build the URL to look like this:
http://pillbox.nlm.nih.gov/PHP/pillboxAPIService.php?key=My_API_KEY&ingredient=diovan
public String makeServiceCallPillBox(String url, int method,
String api, String drugName)
{
String resultEnitity = null;
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpEntity entityResult = null;
// Checking http request method type
if (method == POST)
{
HttpPost httpPost = new HttpPost(url);
// Butild the parameters
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("key", api);
builder.addTextBody("ingredient", drugName);;
final HttpEntity entity = builder.build();
httpPost.setEntity(entity);
Log.d("url", httpPost.toString());
httpResponse = httpClient.execute(httpPost);
Log.d("post", builder.toString());
Log.d("post2", entity.toString());
entityResult = httpResponse.getEntity();
resultEnitity = EntityUtils.toString(entityResult);
Log.d("result", resultEnitity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultEnitity;
}
Any help is appreciated.
I am using this code for sending push notification in Android devices. http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ Its work. But they are using php in server side. and My Server side is JAVA. so I am trying to create jUnit testing for that. so my server will send push notification. But i have not idea about that. I tried by post method but did not work. getting 401 error.
String regID = "";
pairs.add(new BasicNameValuePair("registration_ids",regID));
pairs.add(new BasicNameValuePair("data","test"));
pairs.add(new BasicNameValuePair("key","my key"));
String url = "https://android.googleapis.com/gcm/send";
String data = makePostCall(url, pairs);
Please suggest to me in jUnit.
I was passing incorrect params. It should be header and body. This is way which I used and working nice.
public class SendPushNotification {
public static void main(String[] arg){
PushNotification pushNoti = new PushNotification();
//collect the device_tokens into JSONArray.
// device_tokens is the tokens of user where we needs to send the push Messages.
String id = "APA9******WVWA";
JSONArray deviceTokenArray = new JSONArray();
// if you want to send more than one device then you have to
// add more ids into JSONArray by using put method.
deviceTokenArray.put(id);
try {
pushNoti.sentPushIntoAndroid(deviceTokenArray, "I Love to my sister and sending a push message in Android Device");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and that is another class which is using HTTPHeader and HTTPBody.
public class PushNotification {
public void sentPushIntoAndroid(JSONArray device_token, String message)
throws JSONException {
HttpPost httppost = new HttpPost("https://android.googleapis.com/gcm/send");
StringEntity stringentity = new StringEntity(generateJSONBodyForHTTPBody(device_token, message).toString(), "UTF-8");
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("Authorization", "key=AI**********Mo"");
httppost.setEntity(stringentity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String strresponse = null;
if (entity != null) {
strresponse = EntityUtils.toString(entity);
displayLog("HTTP Response ", strresponse);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private JSONObject generateJSONBodyForHTTPBody(JSONArray device_token, String message) throws JSONException {
JSONObject jObj = new JSONObject();
jObj.put(CommonUtilities.REGISTRATION_ID, device_token);
JSONObject dataJson = new JSONObject();
//NOTE:- In Client side, you have to retrieve below param by using getBundle().getString("id") like it. so it will retrieve the id and do for other params too like as i did for id.
dataJson.put("id", "testingID");
dataJson.put("type", "testingType");
dataJson.put("imglink", "testingimgLink");
dataJson.put("seolink", "testingseoLink");
dataJson.put("msg", "Lata Bhulli");
jObj.put("data", dataJson);
displayLog("JSONObject", jObj.toString());
return jObj;
}
private void displayLog(String tag, String message) {
System.out.println(tag+" "+message);
}
Note:- If you are getting compile error than you have to use latest HTTP Libraries and used in libs folder then add all in build path.
I've created basic android apps in various programming classes that I have taken before using Eclipse and the Java Android SDK.
The app that I'd like to create would require users to enter information that would later be analyzed. I want people to be able to compare this data with other people's data so I'd like every entry that users make to be submitted to a database to later be queried when a person attempts to compare their data.
I'd like direction for how to accomplish this. Should I find a free hosting site and set up a Sql server or is there a better way to accomplish this?
Edit: Just for fun.
I am a very beginner android developer, and I have found that using cloud-stored online database like mongolab.com is very friendly for user submitted data. The communication between database and server will have to be done through JSON parsing and URI requests.
Here is example of code you can bind to a button that will send object stored in field tempData:
public void send(View view) {
String apiURI = "https://api.mongolab.com/api/1/databases/MYDATABASE/collections/USERSUBMITTEDDATA?apiKey="
+ apiKey;
try {
// make web service connection
final HttpPost request = new HttpPost(apiURI);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string with GSON library
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(tempData);
String json = gson.toJson(jsonElement);
StringEntity entity = new StringEntity(json);
Log.d("****Parameter Input****", "Testing:" + json);
request.setEntity(entity);
// Send request to WCF service
final DefaultHttpClient httpClient = new DefaultHttpClient();
new AsyncTask<Void, Void, Void>() {
#Override
public Void doInBackground(Void... arg) {
try {
HttpResponse response = httpClient.execute(request);
Log.d("WebInvoke", "Saving: "
+ response.getStatusLine().toString());
// Get the status of web service
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
// print status in log
String line = "";
while ((line = rd.readLine()) != null) {
Log.d("****Status Line***", "Webservice: " + line);
}
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
return null;
}
}.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
And here is an example of code used to retrieve elements in the database:
public void load() {
String apiURI = "https://api.mongolab.com/api/1/databases/MYDATABASE/collections/USERSUBMITTEDDATA"
+ "?apiKey=" + apiKey;
Log.d("****Status Line***", "" + apiURI);
try {
// make web service connection
final StringBuilder builder = new StringBuilder();
final HttpGet request = new HttpGet(apiURI);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
final DefaultHttpClient httpClient = new DefaultHttpClient();
new AsyncTask<Void, Void, String>() {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
doSomethingWithReceivedData(result); //THIS METHOD IS DEFINED IN BODY OF YOUR ACTIVITY
}
#Override
public String doInBackground(Void... arg) {
try {
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.d("****Status Line***", "Success");
return builder.toString();
} else {
Log.d("****Status Line***",
"Failed to download file");
}
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
return null;
}
}.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
You should have a data base to store the data. Like mentioned above, the data base is good to be in MySQL (SQL). Your application should have a method that can POST the results to the server, where the server will read the string send and retrieve and store the data.
A good start is to read about JSON
and read also about Asynctask
Also you need to know how to build your sever part. A good idea is to start with PHP, but I am not an expert on that field.
I hope this helps you start your project.
Simple, no DB required.
Usergrid by Apigee is exactly what you are looking for!
You can store each user's details
Retrieve stored data
Send events and receive event callbacks across devices
Best of all - no server side code. Only APIs
FYI This is the direction you should be heading even if you know how to code a server.
PS: I don't work for apigee or usergrid.
I want to upload a txt file to a website, I'll admit I haven't looked into it in any great detail but I have looked at a few examples and would like more experienced opinions on whether I'm going in the right direction.
Here is what I have so far:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
public String postPage(String url, String data, boolean returnAddr) {
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();
return ret;
}
And I call it as follows:
postPage("http://www.testwebsite.com", "data/data/com.testxmlpost.xml/files/logging.txt", true));
I want to be able to upload a file from the device to a website.
But when trying this way I get the following response back.
HTTP/1.1 405 Method Not Allowed
Am I trying the correct way or should I be doing it another way?
That code looks reasonable, the error is from the server and indicates that POST is not allowed for that page.
You're sending the literal string "data/data/com.testxmlpost.xml/files/logging.txt". If you want to post a file, use a FileEntity.