Hello,

I''m trying to connect to my drupal website on my android 2.2 mobile. I've installed drupal 7 and the services module and created the endpoint. I think i got everything configured properly, however it seems that I can't even make the right call "system.connect". Has there been any chances since 6.0 version?
I'm using this XMLRPC library: http://code.google.com/p/android-xmlrpc/ I'm not sure how to call "system.connect", needed parameters? return values? I can't find any answer on how to call it, otherwise i'll have another look at some 6.0 tutorials and see how they did it.

Would it be possible to sent an image via XMLRPC to drupal and create a new node with a UI Field Image and save node the image taken via my mobile? Thats my target/aim/project :)

Would appreciate any help to guide me in the right direction :) Thanks.

Comments

luisgic’s picture

Hi, Volvo I am do it, I think the Services 3.x for Drupal7 tutorials is too old. But I learning Services 3.x for Drupal7. I need help too.
I interesting Services3.x for android mobile.

kylebrowning’s picture

Im not sure how to do it with XMLRPC, but its working perfectly by POSTing to system/connect on the REST server

luisgic’s picture

Sorry, kylebrowning I don't know too.
I'm use REST server can login, but I can't register though the path: www.domain.com/myserv/user
It error: [code] => 401 [error] => Unauthorized: Access denied for user 0 "anonymous"
I don't understand the code in the path:sites/all/modules/services/resources/user_resource.inc line:209 follow:
202
203 // Any logged in user is by default authenticated,
204 // and leaving this role set in the user's roles array
205 // causes big problems because of a FAPI hack that controls
206 // this checkbox on the user create and edit form (and thus
207 // causes problems with drupal_execute()). Therefore we just
208 // force it to 0 here.
209 if (isset($account->roles[2])) {
210 $account->roles[2] = 0;
211 }

have anybody help. how to create user or register
my test PHP code follow:

$account = array(
'name' => 'zoo',
'pass' => 'zoo',
'mail' => 'zoo@**.com',
);
$data = array(
'account' => $account,
);
$data = http_build_query($data, '', '&');
$optionss = array(
'headers' => $headers,
'method' => 'POST',
'data' => $data,
'max_redirects' => 3,
'timeout' => 30.0,
'context' => NULL,
);
$response = drupal_http_request($base_url . '/user', $optionss);

kylebrowning’s picture

Do anonymous users have the permission to create user accounts?

Volvo’s picture

@Kyle
I haven't tried the REST server yet. What are the differences between XMLRPC and REST? and can i achieve my goal to create a new node and attach a photo to that node from Android.

kylebrowning’s picture

Yes you can do the same with REST, you just dont need a specific client like xmlrpc. With REST you just send a HTTP request with some data and boom, your done. You can do a lot of testing to an API just via a web browser, although theres various HTTP Clients out there.

luisgic’s picture

yes,I want to register a user from android with REST.Can you help me?

Volvo’s picture

I'm using REST communication now. After some fiddeling managed to connect and succesfully login my account. Which is pretty neat :)
Now I want to create a new content type. Which createria do i need to add to the parameters of a POST for a succesfull creation? I guess title, body, published, time? then I have to search how to fill/sent my image/photo, lovely research :) Any ideas?

kylebrowning’s picture

I know this isnt a lot of information, but you can look in TESTS on how its handled. BAsically you need to send all of the data you listed, and to fill in an image /photo that data would look like this

&node[status]=1&node[title]=atitle&node[type]=article&node[language]=und&node[date]=now&node[body][und][0][value]=smallbody&node[field_image][und][0][fid]=11

Where fid is the ID of the file uploaded from the post to /APIENDPOINT/file

Volvo’s picture

Thanks, that got me in the right direction i think. Although I'm stuck with the permission i think. I'm gettin an error: Unauthorized: Access denied for user 0 "anonymous".
I'm sending the sessionID which I got from when i loggedin wtih my admin account. I can't see any user validation in the tests in the services module. I tried sending sessid/uid, but didnt help much.

Rest CreatePhoto = new Rest(SERVER_URL + "/rest/node");
CreatePhoto.AddParam("sessid", sessionID);     // testing
CreatePhoto.AddParam("node[status]", "1");
CreatePhoto.AddParam("node[title]", "a title");
CreatePhoto.AddParam("node[body][und][0][value]", "bodytest");
CreatePhoto.AddParam("node[type]", "mobile_photo");
CreatePhoto.AddParam("node[language]", "und");
CreatePhoto.AddParam("node[date]", "now");
CreatePhoto.AddParam("node[name]", USER_LOGIN);
CreatePhoto.AddParam("uid", "1");	      	// testing
CreatePhoto.Execute(RequestMethod.POST);
kylebrowning’s picture

It migtht be required that you use a cookie, although im uncertain. Ill take a look later.

luisgic’s picture

@ Volvo
where you use REST server? android?

Volvo’s picture

@luisgic, using REST Server from services module and yeah creating an app for android.

@kyle, I've did some testing and edited the permission for guest to create new content (mobile_photo). My new content is created. But this can't be the case for running live website. Its correct that i need to send the sessid again to make sure i'm logged in right?

Right now i'm trying to upload the image via /APIENDPOINT/file, but after some trying out, dunno how to send my image to it? Do i need to encode it and which parameters do i need to sent?. Like you said, use the fid (which i probably get as response) for the photo field. Also the permission issue applies for sending /apiendpoint/file as well.

Thanks.

kylebrowning’s picture

You need to set the Cookie header, with the information thats returned from user/login.

Session based authentication with just a sessid is no longer supported I believe. You need to set your cookie

luisgic’s picture

I come from China. Today is the Spring Festival. Happy New Year to everybody!

@ Volvo
Can you give me you email? I am creating app for android from Services module.

Volvo’s picture

@Kyle, I haven't tried that yet, gonna do try to find out how todo that. Have you got a short description in how to sent a photo to Drupal to the APIendpoint/file ?

@luisgic, Why do you need my email, I'm not the person that can give you any directions as i'm learning myself. if you have any questions/problems, create a new issue orso, anyway please stay on topic.

luisgic’s picture

You are right! thanks

luisgic’s picture

@volvo, at #10: Rest class are you create? I think your method is grade。 can you show it in this web.

@Kyle, at #4: you said:Do anonymous users have the permission to create user accounts?
how to set the permission? I am set in drupal7,but give the msg too :Access denied for user 0 "anonymous".

Volvo’s picture

@luisgic, its a class i found somewhere for REST communication. I shall post the link to it later."I think your method is grade" I don't understand this.
In drupal go to the admin dashboard area, People and Permissions tab is on the top right. There you can edit the permissions for anonymous.

luisgic’s picture

@Volvo "I think your method is grade" I mean your Class is good, it can reuse everytime to connect.wait for your link :-)

gdd’s picture

There is documentation on how to make authenticated requests to the REST server at

http://drupal.org/node/910598

This example uses PHP, but the important thing is setting the 'Cookie' header with session name and session data on EVERY request after you login.

AS far as sending photos, right now they need to be Base64 encoded.

Volvo’s picture

Ah, missed that example. I've tried to use the 'Set-Cookie' name and used the value session_name (something similair), values like SESS5913ad7ed....
So the header needs to contain a namepairvalue: 'Cookie' and the session_name value from the login.

Yeah, I already encoded my photos to base64 in a long string. I think i tried to pair it with the name 'File' and sent it to endpoint /file. (After I changed the permission for anymounous), i got a 200 value back. and the response I got was "' false". No actual JSON with a fid or anything like that. What else needs to be sent to the /file endpoint. Any mandatory fields, like uid? time?

@luisgic:
The link: http://lukencode.com/2010/04/27/calling-web-services-in-android-using-ht...

luisgic’s picture

StatusFileSize
new47.93 KB
new45.45 KB

Thanks for sharing the link,
I want to register a user, but don't how to do.
follow is my code. but it don't works. help me please...

public StringBuilder servicesUserCreate() {
StringBuilder builder = new StringBuilder();
try {

HttpClient client = new DefaultHttpClient();
String url = "http://192.168.1.2/drupal7/myserv/user";
class Account{
public String name;
public String pass;
public String mail;

}
Account account = new Account();
account.name = "yyy";
account.pass = "yyy";
account.mail = "yyy@google.com";
Map data = new HashMap();
data.put("account", account);

HttpPost httpPost = new HttpPost(url);

ArrayList postData = new ArrayList();
for (Map.Entry m: data.entrySet()){
postData.add(new BasicNameValuePair(m.getKey(),m.getValue().toString()));
}

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, HTTP.UTF_8);
httpPost.setEntity(entity);

HttpResponse response = client.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
for (String s = reader.readLine(); s != null; s = reader.readLine()) {
builder.append(s);
}

return builder;

} catch (Exception e) {
Log.v("url response", "false");
e.printStackTrace();
}
return null;

}

#and I set in the drupal7 like in the attachments
thanks

Volvo’s picture

I tried the Cookie header option to verify my permissions, but it didnt work. I've added the following code to the request I was doing. CookieID is the 'session_name' which i got from an successfull login.
UploadPhoto.AddHeader("Cookie", CookieID);

As the photo concern, i've encoded it with base64 and put it under 'file' name:
UploadPhoto.AddParam("file", Base64.encodeToString(bitmapByteArray, Base64.DEFAULT));
Is this the only thing I need to sent? Tried this as well
UploadPhoto.AddHeader("Content-Type", "application/x-www-form-urlencoded");
Thanks

@luisgic, I had a quick look over it, and I don't think you understand REST system with JSON ect. Might be better to open a other issue regarding your problem.

Volvo’s picture

I'm trying to pick it up again. Ive managed to get arround the cookie thing. Seems that I didnt looked thouroughly enough and spotted the : name and session id, anyway.
Could anyone help me to kick me in the direct direction to upload a photo (encoded byte array) to Drupal.

Kyle mentioned earlier. "Where fid is the ID of the file uploaded from the post to /APIENDPOINT/file"
What kind of information do i need to supply the file endpoint? And with which endpoint do I need to give permission in Drupal?

Thanks

ygerasimov’s picture

@Volvo the best source to look for example are tests. Here is piece of code that uploads image (in php of course):

    // Create file argument with data.
    $file = array(
      'filesize' => filesize($this->testfile->uri),
      'filename' => $this->testfile->filename,
      'file' => base64_encode(file_get_contents($this->testfile->uri)),
      'uid' => $this->privileged_user->uid,
    );

    // Create file with call.
    $result = $this->servicesPost($this->endpoint->path . '/file', array('file' => $file));

So in order to create a file you need to base64 encode content of the file and pass it in array with filesize, filename and user id.

Hope this helps.

check_writer’s picture

Hello, I'm a newbie to Drupal and PHP but have managed to install D7 and Services 3.x (also enabled it both XMLRPC and REST services)... drupal itself runs fine and i can access drupal at http://myserver/drupal/.

I'd like to use the XMLRPC or REST services to import data into drupal but I can't seem to get the correct URL for XMLRPC or REST and I've tried the following which fails: at http://myserver/drupal/services/xmlrpc AND http://myserver/?q=services/xmlrpc ... the same thing for REST http://myserver/drupal/services/rest/.... AND http://myserver/drupal/?q=services/rest...

Tell me what the correct URLs for XMLRPC and REST should be ?

thanks.

marcingy’s picture

It depends on what you name your endpoints there is no specific url.

check_writer’s picture

Sorry, I'm not sure I understand.

Drupal works fine @ http://myserver/drupal. I simply followed in the instructions for the Services module, enabled XMLRPC and REST in the configuration page, hit save. and I assummed I can write a small XMLRPC client app to access a simple call like user.login or system.connect @ http://myserver/drupal/?q=services/xmlrpc

Was there something I missed? where was I supposed to name my end points?

thanks.

marcingy’s picture

Which version of services are you using?

check_writer’s picture

I've tried 3.x-rc3 and 3.x-dev both with same issue.

marcingy’s picture

Ok so 3.x you need to set up an end point. The docs you read likely refered to 2.x. The link to set up an endpoint can be found here admin/structure/services on rc4 at least.

check_writer’s picture

Thanks! that worked.

Now, I'll certainly RTFM later, but is there documentation on these functions and expected arguments?

I did the following and got error 500:

-- groovy code --
import groovy.net.xmlrpc.XMLRPCServerProxy
XMLRPCServerProxy serverProxy = new XMLRPCServerProxy("http://myserver/drupal/xmlrpc")
def session = serverProxy.invokeMethod ("system.connect",[])
def user =serverProxy.invokeMethod ("user.login",[session, 'admin','admin'])

----error occurred on system.connect line---
XML-RPC call Failure: fault string = "Server returned HTTP response code: 500 for URL: http://myserver/drupal/xmlrpc", fault code = 0

Thanks again.

marcingy’s picture

Cool - Hehe this might be help https://gist.github.com/affc9864487bb1b9c918 it is rest based but the args are the same.

marcingy’s picture

Or look at the tests that ship with services for examples admittely most are REST based. If you can use rest I would advise that to be honest as the rest server has lots of tests.

check_writer’s picture

Thanks!

Ok, I'm able to create nodes (using XMLRPC) without an issue however I'm not able to create them as a logged-in user, so my nodes are being created as Anonymous etc. I'm able to get a sessionID and sessionName from user.login but how do I call node.create so it has the user info in it?

I tired this and it failed with a 406 http error.

def args = [ title:'Sample Auto Page', body:[und:[[value:'This is a post @ '+new Date()]]] ,
type:'conceptual_meta_type', field_bu:[und:[[value:'Retail']]] ]
def sessid = 'Sr6d_W3DHq0kq6gGqsQcS2IDaWmps2epVHoBaPuc4bY' // got this from the user.login call

serverProxy.invokeMethod ('node.create', [sessid, args]);

any ideas?

thanks in advance.

felixSchl’s picture

so, check_writer, did you manage to solve the issue?

marcingy’s picture

Status: Active » Fixed

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

Volvo’s picture

I've managed to have fully functionality app which let me upload photos to the file Endpoint and recieving an 'fid'. Also creating new content works fine and everything works at it supposed to work however I need to make all the calls anonymous instead of being logged in.

Ive created all the functionality connect, login (capture the cookie information for further calls), file, add node, logout ect. But the most important calls: file and add node, for those to work, I need to set the permissions to anonymous.

I read somewhere that the authentication is done by Drupal (so I guess done by the cookie parameter). I also found this, regarding a cookie issue: http://drupal.org/node/1133084 #1133084: Use of Cookie header for authentication means that remote jQuery clients can not authenticate(I haven't tried this module yet)
This is the information from the Modules, regarding the authentication:
Services - authentication
'Session Authentication' (7.x-3.0-rc1) is enabled.
When editing a service with 'Edit Authentication' I'm getting the message: 'No authentication modules are enabled, all requests will be anonymous.'

At the moment the permission are set to anonymous for the following modules:
Node:
[content_name]: Create new content
Services:
Save file information

Thanks for any information leading towards a solution.

Volvo’s picture

Status: Closed (fixed) » Active
kylebrowning’s picture

Status: Active » Closed (fixed)