2010-02-19 6 views
6

Estoy tratando de implementar http async en java. Aquí está el parte importante del código:recibiendo una extraña excepción tratando de implementar http asincrónico en el motor de la aplicación de google para java

for (String urlString : urls) 
{ 
    // TODO: try and get rid of these two heap allocations 
    url = new URL(urlString); 
    request = new HTTPRequest(url); 
    request.addHeader(userAgentHeader); 
    request.addHeader(authorizationHeader); 
    request.addHeader(acceptEncodingHeader); 
    request.addHeader(acceptCharsetHeader); 
    responses.add(URLFetchServiceFactory.getURLFetchService().fetchAsync(reques t)); 
    apiCallsMade++; 
} 
for (Future<HTTPResponse> futureResponse : responses) 
{ 
    parseResponse(new String(futureResponse.get().getContent())); 
} 

me siguen dando este error:

com.google.apphosting.api.ApiProxy$CallNotFoundException: The API package 'urlfetch' or call 'Fetch()' was not found.

Busqué a cualquier frasco que faltaban en la ruta de clase, pero no vi nada que faltan . ¿Sabes en qué jar está el código? Busqué en Google el error y también busqué a través de este grupo pero no encontré nada. Gracias, David

Respuesta

8

Con Google appengine, no se puede usar esas API en las aplicaciones java locales. Esto funcionará solo cuando desarrolles e implementes aplicaciones web usando google appengine sdk. Esto está diseñado para funcionar de esta manera solamente.

Al usar esta API, utilizará el cliente http y, en el caso del entorno del motor de la aplicación, hará uso de la infraestructura de Google. Si aún desea probar la aplicación diseñada para google appengine, podría considerar usar LocalURLServiceFactory.

0

Mi única conjetura es que se debe a que Future no se completó antes de intentar acceder a su respuesta. ¡Pero eso es una suposición completa y absoluta!

Tal vez revise cada uno de los futureResponses.isDone() y .isCancelled() antes de acceder a su .get().

+1

En realidad resultó que no se puede usar el jar del motor de la aplicación en una aplicación de consola. el código funciona muy bien en la configuración típica de un proyecto de motor de aplicación. – davidjnelson

1

aquí es un simple ejemplo de trabajo de cómo hacer esto que he creado para mi blog:

package org.appEngineAsync.server; 



import java.io.ByteArrayInputStream; 

import java.io.ByteArrayOutputStream; 

import java.net.URL; 

import java.util.ArrayList; 

import java.util.List; 

import java.util.concurrent.CopyOnWriteArrayList; 

import java.util.concurrent.Future; 

import org.appEngineAsync.client.GreetingService; 

import com.google.appengine.api.urlfetch.HTTPHeader; 

import com.google.appengine.api.urlfetch.HTTPRequest; 

import com.google.appengine.api.urlfetch.HTTPResponse; 

import com.google.appengine.api.urlfetch.URLFetchServiceFactory; 

import com.google.gwt.user.server.rpc.RemoteServiceServlet; 



@SuppressWarnings("serial") 

public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService 

{ 



private HTTPRequest request = null; 

HTTPHeader acceptCharsetHeader = new HTTPHeader("Accept-Charset", "utf-8"); 

// All three of these data types are synchronized for thread safety 

List<Future<HTTPResponse>> responses = new CopyOnWriteArrayList<Future<HTTPResponse>>(); 

protected List<String> tempSingleUrl = new CopyOnWriteArrayList<String>(); 

StringBuffer sb = new StringBuffer(); 



public String greetServer(String input) throws Exception 

{ 

List<String> urlsToFetchInParrallel = new ArrayList<String>(); 



urlsToFetchInParrallel.add("http://gdata.youtube.com/feeds/api/channels?q=" + input + "&start-index=1&max-results=10&v=2"); 

urlsToFetchInParrallel.add("http://gdata.youtube.com/feeds/api/channels?q=" + input + "&start-index=11&max-results=10&v=2"); 

urlsToFetchInParrallel.add("http://gdata.youtube.com/feeds/api/channels?q=" + input + "&start-index=21&max-results=10&v=2"); 

urlsToFetchInParrallel.add("http://gdata.youtube.com/feeds/api/channels?q=" + input + "&start-index=31&max-results=10&v=2"); 

urlsToFetchInParrallel.add("http://gdata.youtube.com/feeds/api/channels?q=" + input + "&start-index=41&max-results=10&v=2"); 

urlsToFetchInParrallel.add("http://gdata.youtube.com/feeds/api/channels?q=" + input + "&start-index=51&max-results=10&v=2"); 

urlsToFetchInParrallel.add("http://gdata.youtube.com/feeds/api/channels?q=" + input + "&start-index=61&max-results=10&v=2"); 

urlsToFetchInParrallel.add("http://gdata.youtube.com/feeds/api/channels?q=" + input + "&start-index=71&max-results=10&v=2"); 

urlsToFetchInParrallel.add("http://gdata.youtube.com/feeds/api/channels?q=" + input + "&start-index=81&max-results=10&v=2"); 

urlsToFetchInParrallel.add("http://gdata.youtube.com/feeds/api/channels?q=" + input + "&start-index=91&max-results=10&v=2"); 



return performHttpRequest(urlsToFetchInParrallel); 

} 



// pass in 10 urls at a time 

private final String performHttpRequest(List<String> urls) throws NumberFormatException, Exception 

{ 

URL url = null; 

request = null; 

byte[] tempBuffer = null; 

byte[] buffer = null; 

ByteArrayInputStream memoryStream = null; 

ByteArrayOutputStream baos = null; 

final int buffSize = 8192; 

int size = 0; 

sb.setLength(0); 

responses.clear(); 



try 

{ 

for (String urlString : urls) 

{ 

url = new URL(urlString); 

request = new HTTPRequest(url); 

request.addHeader(acceptCharsetHeader); 

responses.add(URLFetchServiceFactory.getURLFetchService().fetchAsync(request)); 

} 

for (Future<HTTPResponse> futureResponse : responses) 

{ 

try 

{ 

memoryStream = new ByteArrayInputStream(futureResponse.get().getContent()); 

tempBuffer = new byte[buffSize]; 

baos = new ByteArrayOutputStream(); 

while ((size = memoryStream.read(tempBuffer, 0, buffSize)) != -1) 

{ 

baos.write(tempBuffer, 0, size); 

} 

buffer = baos.toByteArray(); 

} catch (Exception ex) 

{ 

// TODO: log or take other action 

return null; 

} finally 

{ 

try 

{ 

baos.close(); 

} catch (Exception ex) 

{ 

// TODO: log 

} 

} 



// TODO: put this on one line when done debugging 

String responseString = new String(buffer, "UTF-8"); 

sb.append(responseString); 

} 

// TODO: put this on one line when done debugging 

String allResponsesString = sb.toString(); 

return allResponsesString; 

} catch (Exception ex) 

{ 

// TODO: log 

return null; 

} finally 

{ 

try 

{ 

request = null; 

url = null; 

memoryStream = null; 

tempBuffer = null; 

baos = null; 

} catch (Exception ex) 

{ 

// TODO: log 

return null; 

} 

} 

} 

} 
Cuestiones relacionadas