Get Request Não funciona

3 respostas
guisantogui

Pessoal estou tentando fazer um request para um servidor que vai me retornar uma mensagem em json, mas ao rodar o metodo "execute" da classe DefaultHttpClient o sistema sai do bloco try, sem estourar nenhuma exeção (Tratei até Exception e não cai no catch), e simplesmente vai pro return do método. segue o fonte:

private String getItemsList(){

                String appUrl = "http://localhost:3000/items.json";
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet get = new HttpGet(appUrl);
		StringBuilder sb = null;
		try {

			HttpResponse response = httpClient.execute(get);
			HttpEntity httpEntity = response.getEntity();
			
			InputStream is = httpEntity.getContent();
			
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			sb = new StringBuilder();
		    String line = null;
			
		    while ((line = rd.readLine()) != null) {
		        sb.append(line + "\n");
		    }
		    
		    is.close();
		    
		    //TODO test the return

		}
		catch (ClientProtocolException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		catch (Exception e){
			e.printStackTrace();
		}
		
		
		return sb.toString();
	}

Brigadão pessoal!

3 Respostas

drsmachado

E quando debuga, o que rola?

davidbuzatto

Vc só precisa pegar o json?
Tenta isso. Bem mais simples.

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

/**
 *
 * @author David Buzatto
 */
public class Foo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        try {
            
            URL u = new URL( "http://www.uol.com.br/" );
            URLConnection uc = u.openConnection();
            Scanner s = new Scanner( uc.getInputStream() );
            StringBuilder sb = new StringBuilder();
            
            while ( s.hasNextLine() ) {
                sb.append( s.nextLine() ).append( "\n" );
            }
            
            System.out.println( sb.toString() );
            
        } catch ( MalformedURLException exc ) {
            exc.printStackTrace();
        } catch ( IOException exc ) {
            exc.printStackTrace();
        }
        
    }

}
guisantogui

Consegui fazer, bastou trocar o localhost pelo IP da máquina.

Criado 8 de fevereiro de 2012
Ultima resposta 8 de fev. de 2012
Respostas 3
Participantes 3