Make JSON Request from android - java

I have got the following objective-c code which does what I need to do for android but have no idea how to go about it. I need to access a php file on a webserver which will return a JSON string (Dictionary I think?). Below is the code I have for the iPhone version:
+ (NSDictionary *)getNewMission:(int)maxID
{
NSString *serverUrl = #"http://www.website.com/api/api.php";
NSString *methodString = [NSString stringWithFormat:#"\"method\":\"getNewItem\",\"max_item_id\":\"%d\"", maxID];
NSString *postStr = [NSString stringWithFormat:#"json={%#,\"key1\":\"%#\",\"key2\":\"%#\"}", methodString, KEY_1, KEY_2];
return [JsonManager handleJSONRequest:postStr baseURL:serverUrl];
}
+ (NSDictionary *)handleJSONRequest: (NSString*)postString baseURL:(NSString*)baseUrl
{
NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:baseUrl]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSDictionary *results = [data JSONValue];
[data release];
return results;
}
Where should I be looking to help with replicating this in android? I really don't have any meaningful JSON experience especially not in Java/Android. Any help is appreciated.

Here is the code for the Android activity to read from the Web Service and parse the JSON object:
public void clickbutton(View v) {
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("user", "1");
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8080/sample1/" +
"webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("idusers", jObject.getString("idusers"));
map.put("UserName", jObject.getString("UserName"));
map.put("FullName", jObject.getString("FullName"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
For more details see http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php

Related

Android send json to Spring

Spring Controller
#RequestMapping(value = "/login", produces="application/json;charset=UTF-8" ,method = RequestMethod.POST)
#ResponseBody
public int checkLoginInfo(#RequestParam Map<String, String> params) {
User user=new Gson().fromJson((String) params.get("user"), User.class);
return userService.getUserInfo(user);
}
HTML
var params={userid:$("#userid").val(),password:$("#password").val()}
$ajax({method:"post",data:{user:JSON.stringify(params)},url:"foo.bar"});
It worked on website.
But I don't know how to send that Json object for android.
data:{user:JSON.stringify(params)}
I have tested
private static String makeJsonMsg() {
String retMsg = "";
JSONStringer jsonStringer = new JSONStringer();
try {
retMsg = jsonStringer.object()
.key("user").object()
.key("userid").value("userid")
.key("password").value("1234")
.endObject()
.endObject().toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retMsg;
}
like that,
But return 500 error.
Do I need to add header or something else?
The simple way
public void postData(String url,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams );
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(url.toString());
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
How to use
JSONObject requestObject = new JSONObject();
requestObject.put("userid", email);
requestObject.put("password", password);
postData("http://your/login/url",requestObject)
For more info check How to send a JSON object over Request with Android?. Credit of the postData method is for #Sachin Gurnani answer
Hope this helps!!

Cannot send data from Android application to remote database

I want to send registration form data from android application to remote MySQL database but every time I get same error:
java.lang.String can not be converted to JSONObject.
Here is my code:
JSONParser.java
`public class JSONParser
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) throws JSONException
{
try
{
// check for request method
if(method == "POST")
{
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if(method == "GET")
{
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e)
{
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return new JSONObject(json.substring(json.indexOf("{"),json.lastIndexOf("}") + 1));
}
}
`
and here is my mainActivity code
class submitForm extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... args)
{
try
{
String first_name = mFirstname.getText().toString();
String last_name = mLastname.getText().toString();
String username = mUsername.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
String mobile = mMobile.getText().toString();
String country = mCountry.getSelectedItem().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("FirstName", first_name));
params.add(new BasicNameValuePair("LastName", last_name));
params.add(new BasicNameValuePair("Username", username));
params.add(new BasicNameValuePair("Email", email));
params.add(new BasicNameValuePair("Password", password));
params.add(new BasicNameValuePair("Mobile", mobile));
params.add(new BasicNameValuePair("Country", country));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(
url_create_product, "POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// finish();
} else {
// failed to create product
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), " in catch",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
catch (Exception ex) {
Log.e("DIG", ex.toString());
}
return null;
}
}
this is my php file
<?php
// array for JSON response
header('Content-type=application/json; charset=utf-8');
$response = array();
$fname = $_POST['Firstname'];
$lname = $_POST['Lastname'];
$uname = $_POST['Username'];
$email = $_POST['Email'];
$password = $_POST['Password'];
$country = $_POST['Country'];
$mobile = $_POST['Mobile'];
// include db connect class
require_once ('db_connect.php');
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysqli_query("INSERT INTO users(Firstname,Lastname,Username,Email,Password,Country,Mobile) VALUES('$fname', '$lname', '$uname', '$email', '$password', '$country', '$mobile')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User inserted successfully.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
?>
on server side i get the error
undefined index Firstname,Lastname,username,Email,Password...
and in eclipse logcat i get error
java.lang.string can not be converted to JSONObject
You can't access that data in php through POST because it is being sent on the android application through the HTTP header and not over application/x-www-form-urlencoded.
Here's a thread that explains how you can do it:
How to retrieve Request Payload

Android post variables to drupal

Hi I'm writing an app for both iOS and Android to interface with a druapl site. I'm trying to allow users to login to the website and then save the data from successful logins in the preferences of the app. Below I was able to successfully do what I wanted in Cocoa but I have been unable to get it to work in Java. Both code snippets are below. Any help with the java would be greatly appreciated.
I'm just not getting any response at all from the java the response comes back as an empty string when it should be a long JSON response.
Cocoa Login (Working)
NSURL *url = [NSURL URLWithString:#"http://examplesite/api/rest/user/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSData *requestBody = [[NSString stringWithFormat:#"username=%#&password=%#",[userField text],[passField text]] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestBody];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
Java Login (Not Working)
class loginTask extends AsyncTask<Void, Void, Void> {
HttpResponse response;
public loginTask() {
}
#Override
protected Void doInBackground(Void... arg0) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://examplesite/api/rest/user/login");
try {
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "password"));
post.setEntity(new UrlEncodedFormEntity (formparams));
response = client.execute(post);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
//TODO finish the activity
try {
Toast.makeText(Login.this, EntityUtils.toString(response.getEntity(), "UTF-8"), Toast.LENGTH_SHORT).show();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There's things for this like. Drupal iOS sdk and dandy for android
Looking at the examples you've listed you aren't submitting the same payload on iOS and Android.
On iOS you are correctly POSTing form data with username=foo&password=bar, but on android you are asking for the string representation of your JSONObject which is { 'username': 'foo', 'password':'bar' }.
Rather than using a JSONObject you should checkout URLEncodedUtils, in particular the format method.

How to call a json webservice through android

I need to access a .Net web service in Rest format using JSON. I m
pretty new to this concept and very much confused about how this
works....
Any one who can give an overview of this. I need the steps that I
need to follow to use JSON. Right now my doubt is how to use JSON to
grab to output.
This is the simplest way to parse Json web servie
String str="url";
try{
URL url=new URL(str);
URLConnection urlc=url.openConnection();
BufferedReader bfr=new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String line;
while((line=bfr.readLine())!=null)
{
JSONArray jsa=new JSONArray(line);
for(int i=0;i<jsa.length();i++)
{
JSONObject jo=(JSONObject)jsa.get(i);
title=jo.getString("deal_title"); //tag name "deal_title",will return value that we save in title string
des=jo.getString("deal_description");
}
}
catch(Exeption e){
}
Mention Internet permission in android manifest
Gson library can parse your json string automatically to object.
Simple example:
Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};
//(Serialization)
gson.toJson(ints); ==> prints [1,2,3,4,5]
gson.toJson(strings); ==> prints ["abc", "def", "ghi"]
//(Deserialization)
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
==> ints2 will be same as ints
Here is the code for the Android activity to read from the Web Service and parse the JSON object:
public void clickbutton(View v) {
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("user", "1");
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8080/sample1/" +
"webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("idusers", jObject.getString("idusers"));
map.put("UserName", jObject.getString("UserName"));
map.put("FullName", jObject.getString("FullName"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
For more details see http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
you use the json data as follows:
var a=new JSONObject(jsonData);
http://developer.android.com/resources/tutorials/views/hello-mapview.html
Use the data from a to constuct the necessary objects and do the necessary with the same

Android, uploading a photo to host on imgur programatically

I have tried different methods to upload and retrieve a link via imgur but none have been successfull despite looking at the imgur api.
http://api.imgur.com/examples#uploading_java
But the following methods partly works..
im trying to retrieve,
errors: if any errors occured.
link to image: the link to the image hosted
delete link: the link to delete the image hosted
But i only end up with the "delete link", as the others are blank,
check it out:
public void post(String path) {
List<NameValuePair> postContent = new ArrayList<NameValuePair>(2);
postContent.add(new BasicNameValuePair("key", DEV_KEY));
postContent.add(new BasicNameValuePair("image", path));
String url = "http://api.imgur.com/2/upload";
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < postContent.size(); index++) {
if(postContent.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(postContent.get(index).getName(), new FileBody(new File (postContent.get(index).getValue())));
} else {
// Normal string data
entity.addPart(postContent.get(index).getName(), new StringBody(postContent.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
mImgurResponse = parseResponse (response);
Iterator it = mImgurResponse.entrySet().iterator();
while(it.hasNext()){
HashMap.Entry pairs = (HashMap.Entry)it.next();
Log.i("INFO",pairs.getKey().toString());
if(pairs.getValue()!=null){
reviewEdit.setText(pairs.getValue().toString());
Log.i("INFO",pairs.getValue().toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private Map<String,String> parseResponse(HttpResponse response) {
String xmlResponse = null;
try {
xmlResponse = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (xmlResponse == null) return null;
HashMap<String, String> ret = new HashMap<String, String>();
ret.put("error", getXMLElementValue(xmlResponse, "error_msg"));
ret.put("delete", getXMLElementValue(xmlResponse, "delete_page"));
ret.put("original", getXMLElementValue(xmlResponse, "original_image"));
return ret;
}
private String getXMLElementValue(String xml, String elementName) {
if (xml.indexOf(elementName) >= 0)
return xml.substring(xml.indexOf(elementName) + elementName.length() + 1,
xml.lastIndexOf(elementName) - 2);
else
return null;
}
All i get back in the end is a hashmap mImageResponse with only the delete link...
any ideas on what im doing wrong?
The fix to this was merely to change the URL to: imgur.com/api/upload.xml

Categories