HTTP authentication in J2ME
Asked Answered
R

3

7

I'm trying to create a J2ME app, which talks to webserver using HttpConnection connector.

When I am talking to the WebServer, I have to authenticate using Basic HTTP auth, which normally goes like

http://username:[email protected]/rest/api/method

But in J2ME, when I construct a url of this form, it doesn't work.

I also tried adding request property, hc = (HttpConnection) Connector.open(url); hc.setRequestProperty("User", "alagu"); hc.setRequestProperty("pass", "mypassword");

but didn't work.

Has anyone done j2me based HTTP auth before? Thanks in advance.

Rheumatic answered 4/6, 2009 at 14:18 Comment(2)
hey hi Alagu, how you solved this problem. How you done Basic Auth., can you please give me idea how to done basic auth. in j2me... pleaseAlmund
@SajidShaikh I tried wds's solution and it worked.Rheumatic
V
11

It could be J2ME has no support for basic authentication, I might be wrong. If you want to try just setting the authentication header in the request yourself you'll likely need a different header then what you're using.

From the rfc:

To receive authorization, the client sends the userid and password, separated by a single colon (":") character, within a base64 [7] encoded string in the credentials.

[...]

If the user agent wishes to send the userid "Aladdin" and password "open sesame", it would use the following header field:

 Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

So just create the string "User:Password", base64 encode it and then call setRequestProperty("Authorization", "Basic "+ encodedUserAndPass)

Vosges answered 4/6, 2009 at 15:29 Comment(1)
To make matters more fun, J2ME doesn't include a Base64 encoder in MIDP 2.0. Some vendors provide their own, so be careful importing them (Sun's WTK has one, but it's only in the WTK). From the looks of it, you're best off including your own, like: java.sun.com/docs/books/j2mewireless/examples/src/examples/…Centralization
L
3

Incredible, it works like a charm:

String url = "hppt://www.example.com";
HttpConnection hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Authorization", "Basic "+ BasicAuth.encode("user", "password"));
Leavening answered 27/7, 2009 at 0:1 Comment(0)
A
1

I used Bouncy Castle cryptographic library's Base64 Encoder/Decoder. It is very powerful in overcoming lots of limitations set by Java ME/J2ME API. It's open-source and it works for both Java ME and Android.

Artair answered 30/5, 2011 at 21:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.