November 2010 Archives

Use JDO and RESTful web services at GAE. Usually need to parser JSON format string by Gson. But, some JDO class doesn't have No-args constructor, public YourClass(){}, and therefore the gson instance will throw out exception, No-args constructor for class XXX does not exit.
There are two ways to fix this problem:
One, add No-args constructor in the JDO class.
The other is use InstanceCreator to instead a no-argument constructor.
Example:

public class YourClassInstanceCreator implements InstanceCreator<YourClass> {
 public YourClass createInstance(Type type) {
   return new YourClass(null, null, null, null);
 }
}

Then build the gson instance through GsonBuilder, like
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(YourClass.class, new YourClassInstanceCreator());
Gson gson = builder.create();
stoken = gson.fromJson(json, YourClass.class);

Call Plurk API by HttpClient 4

| 1 TrackBack

之前的噗浪(Plurk)期貨即時訊息文章中,說道IM發噗會有掉噗情況,目前改用Plurk Api後,情況有改善。程式如下:

import java.io.IOException;

import java.net.URLEncoder;


import org.apache.http.HttpHost;

import org.apache.http.HttpResponse;

import org.apache.http.HttpStatus;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.CookieStore;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.conn.params.ConnRoutePNames;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;


public class PlurkApi {


private static final String API_KEY = "KEYSTRING";

static boolean use_proxy = false;

static String PROXY_NAME = "proxy.hinet.net";

static int PROXY_PORT = 80;

static CookieStore cookiestore;

static final String username= "youraccount";

static final String password= "yourpassword";

private volatile static PlurkApi plurk;

private PlurkApi(){}

public static PlurkApi getInstance(){

if (plurk == null) {

synchronized (PlurkApi.class){

if (plurk == null) {

plurk = new PlurkApi();

}

}

}

return plurk;

}


    public static String getApiUri(String uri) {

        return "http://www.plurk.com/API" + uri;

    }


    public final static void main(String[] args) {

     PlurkApi p = PlurkApi.getInstance();

     p.plurkAdd("API測試111111!");

     p.logout();

    }

    

    public String login() {

     DefaultHttpClient httpclient = new DefaultHttpClient();

        if (use_proxy) {

HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);

httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,

proxy);

}

        

        HttpGet httpget = new HttpGet(getApiUri("/Users/login?"+

                            "api_key=" + API_KEY + "&" +

                            "username=" + username + "&" +

                            "password=" + password

                          ));

        HttpResponse response = null;

String responseString = null;

try {

response = httpclient.execute(httpget);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

cookiestore = httpclient.getCookieStore();

responseString = EntityUtils.toString(response.getEntity());

// 如果回傳是 200 OK 的話才輸出

// System.out.println(responseString);

//

} else {

System.out.println(response.getStatusLine());

responseString = EntityUtils.toString(response.getEntity());

System.out.println(responseString);

}

} catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

httpclient.getConnectionManager().shutdown();

return responseString;

    }

    

    public String plurkAdd(String url) {

     PlurkApi p = PlurkApi.getInstance();

     if (cookiestore == null)

     p.login();

     DefaultHttpClient httpclient = new DefaultHttpClient();

        if (use_proxy) {

HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);

httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,

proxy);

}

        httpclient.setCookieStore(cookiestore);

       

        HttpResponse response = null;

String responseString = null;

try {

String content = URLEncoder.encode(url, "UTF-8");

HttpGet httpget = new HttpGet(getApiUri("/Timeline/plurkAdd?"+

               "api_key=" + API_KEY + "&" +

               "content=" + content + "&" +

               "qualifier=" + "says" + "&" +

               "lang=tr_ch"));

response = httpclient.execute(httpget);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

cookiestore = httpclient.getCookieStore();

responseString = EntityUtils.toString(response.getEntity());

// 如果回傳是 200 OK 的話才輸出

// System.out.println(responseString);

//

} else {

System.out.println(response.getStatusLine());

responseString = EntityUtils.toString(response.getEntity());

System.out.println(responseString);

}

} catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

httpclient.getConnectionManager().shutdown();

return responseString;

    }


    public String logout() {

     PlurkApi p = PlurkApi.getInstance();

     if (cookiestore == null)

     p.login();

     DefaultHttpClient httpclient = new DefaultHttpClient();

        if (use_proxy) {

HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);

httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,

proxy);

}

        httpclient.setCookieStore(cookiestore);

        HttpResponse response = null;

String responseString = null;

try {

HttpGet httpget = new HttpGet(getApiUri("/Users/logout?"+

                     "api_key=" + API_KEY));

response = httpclient.execute(httpget);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

cookiestore = httpclient.getCookieStore();

responseString = EntityUtils.toString(response.getEntity());

// 如果回傳是 200 OK 的話才輸出

// System.out.println(responseString);

//

} else {

System.out.println(response.getStatusLine());

responseString = EntityUtils.toString(response.getEntity());

System.out.println(responseString);

}

} catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

httpclient.getConnectionManager().shutdown();

return responseString;

    }

}

參考:Accessing a security-enabled Google App Engine service from a Java client

如果您撰寫一個GAE servlet,卻是特定權限,如admin,才能執行的service,透過人工輸入網頁是沒多大問題,但如果要用程式去遠端呼叫,卻需要先取得一個token,利用Google Data APIGoogleAuthTokenFactory,呼叫程式如下:

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

import java.util.logging.Logger;


import org.apache.http.HttpHost;

import org.apache.http.HttpResponse;

import org.apache.http.HttpStatus;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.CookieStore;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.params.ClientPNames;

import org.apache.http.client.params.CookiePolicy;

import org.apache.http.conn.params.ConnRoutePNames;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;


import com.google.gdata.client.GoogleAuthTokenFactory;

import com.google.gdata.util.AuthenticationException;


public class AppEngineAPI {

static CookieStore cookiestore;

static final String loginUrl = "http://yours.appspot.com/_ah/login?continue=";

static boolean use_proxy = false;

static String PROXY_NAME = "proxy.hinet.net";

static int PROXY_PORT = 80;

static final String serviceUrl = "http://yours.appspot.com/admin/service?";

static final String username = "your account";

static final String password = "your password";

static final String serviceName = "ah";

static final GoogleAuthTokenFactory factory = new GoogleAuthTokenFactory(serviceName, "", null);

static String token; 

private static final Logger log = Logger.getLogger(AppEngineAPI.class

.getName());


public static void main(String[] args) {

try {

String token = factory.getAuthToken(username, password, null, null, serviceName, "");

String serviceUrl1 = serviceUrl + "a=a&b=b";

String loginUrl1 = loginUrl + URLEncoder.encode(serviceUrl1, "UTF-8") + "&auth=" + token;

httpget(loginUrl1);

} catch (AuthenticationException e) {

log.warning(e.toString());

e.printStackTrace();

} catch (UnsupportedEncodingException e) {

log.warning(e.toString());

e.printStackTrace();

}

}

public static String httpget(String url) {

DefaultHttpClient httpclient = new DefaultHttpClient();

if (use_proxy) {

HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);

httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,

proxy);

}


HttpGet httpget = new HttpGet(url);

// Override the default policy for this request


httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY,

CookiePolicy.BROWSER_COMPATIBILITY);

HttpResponse response = null;

String responseString = null;

try {

response = httpclient.execute(httpget);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

cookiestore = httpclient.getCookieStore();

responseString = EntityUtils.toString(response.getEntity());

// 如果回傳是 200 OK 的話才輸出

// System.out.println(responseString);

//

} else {

System.out.println(response.getStatusLine());

}


} catch (ClientProtocolException e) {

log.warning(e.toString());

} catch (IOException e) {

log.warning(e.toString());

}

httpclient.getConnectionManager().shutdown();

return responseString;

}

}


相關知識:維基百科OpenIDOAuth,Google文件OpenIDOAuth

February 2012

Sun Mon Tue Wed Thu Fri Sat
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29      

Archives

Powered by Movable Type 4.34-en

About this Archive

This page is an archive of entries from November 2010 listed from newest to oldest.

October 2010 is the previous archive.

December 2010 is the next archive.

Find recent content on the main index or look in the archives to find all content.