Método POST em webservice REST

Boa tarde.

Estou desenvolvendo uma aplicação que envia arquivos. O Web service REST foi criado no net beans e a aplicação android no eclipse.

O cliente android está enviando corretamente, pois foi testando o envio para um web service .net.

O problema está em receber o arquivo no meu web service… Vou postar os código para deixar claro que o que fiz.

Aqui o código do cliente:

package br.com;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;  
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;  
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.ByteArrayOutputStream;


public class ConsumidorWSActivity extends Activity implements OnClickListener {
	String URL = "http://10.1.1.2:8080/Provedor/resources/hello";

    String result = "";  
    String deviceId = "xxxxx" ;  
    final String tag = "Your Logcat tag: ";  
    
    Button btnBuscar;
    TextView texto;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnBuscar = (Button) findViewById(R.id.btnBuscar);
        texto = (TextView) findViewById(R.id.texto);
        btnBuscar.setOnClickListener(this);
    }
    
    @Override
	public void onClick(View arg0) {
		try{
			callWebService();
		}
		catch(Exception e){
			Log.e("Erro onClick(): ", e.toString());
			Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
		}
	}
    
    public void callWebService() throws Exception
    {  
    	try
    	{

	        HttpParams httpParams = new BasicHttpParams();
	        HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
	        

	        HttpClient httpclient = new DefaultHttpClient(httpParams);  
	        HttpPost req = new HttpPost(URL);
	        

			String filePath = Environment.getExternalStorageDirectory().toString() + "/3K.pdf";
			String arquivoBase64 = Base64.encodeFromFile(filePath);
	
			Arquivo a = new Arquivo(); // criada uma classe arquivo com o get set
			a.setConteudo(arquivoBase64);
			GsonBuilder b = new GsonBuilder();
			Gson        j = b.create();
			String      json = j.toJson(a);
	        
	        List<NameValuePair> parametros = new ArrayList<NameValuePair>();
	        parametros.add(new BasicNameValuePair("json", json));
	        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parametros,HTTP.UTF_8);
	        req.setEntity(formEntity);
	        
	        HttpResponse response	 = httpclient.execute(req);
	        
	        byte[] bytes = new byte[1024];
	        ByteArrayOutputStream baos = new ByteArrayOutputStream();
	        InputStream inStream = response.getEntity().getContent();
	        int lidos = inStream.read(bytes);
	        while (lidos > 0)
	        {
	        	baos.write(bytes);        	
	        	lidos = inStream.read(bytes);
	        }
	        
	        this.result = new String(baos.toByteArray());
	        Toast.makeText(this, "Enviado ", Toast.LENGTH_LONG).show();
	        
    	}
    	catch(Exception ex)
    	{
    		throw ex;
    	}
    }
} 

Aqui o código do WS:

package com;

import com.google.gson.Gson;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@javax.ws.rs.Path(value = "/hello")

public class Hello {

    @javax.ws.rs.POST
    @javax.ws.rs.Consumes(value = {MediaType.APPLICATION_JSON})
    @javax.ws.rs.Produces(value = {MediaType.TEXT_PLAIN})
    public String ja(@PathParam("json") String json) throws IOException {

        Gson gson = new Gson();
        Arquivo arquivo = gson.fromJson(json, Arquivo.class);

        byte[] decoded = Base64.decodeFromFile(arquivo.getConteudo());

        try {
            File file = new File("teste.pdf");
            BufferedOutputStream bos = null;
            bos = new BufferedOutputStream(new FileOutputStream(file));
            bos.write(decoded);
            bos.close();
            return "Deu Certo";
        } catch (Exception ex) {
            return "Deu Errado!";
        }
    }
}

O teste de web service Restful

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<application xmlns="http://research.sun.com/wadl/2006/10">
<doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 1.8 06/24/2011 12:17 PM"/>
<resources base="http://localhost:8080/Provedor/resources/">
<resource path="/requestToken">
<method id="postReqTokenRequest" name="POST">
<response>
<representation mediaType="application/x-www-form-urlencoded"/>
</response>
</method>
</resource>
<resource path="/hello">
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="json" style="template" type="xs:string"/>
<method id="ja" name="POST">
<response>
<representation mediaType="text/plain"/>
</response>
</method>
</resource>
<resource path="/accessToken">
<method id="postAccessTokenRequest" name="POST">
<response>
<representation mediaType="application/x-www-form-urlencoded"/>
</response>
</method>
</resource>
</resources>
</application>

Quando clico com o botão direito em cima do Hello[/hello] e vou em testar URI do recurso ele abre uma pagina com essa mensagem: HTTP Status 405 - Method Not Allowed

Não sei o que está acontecendo… não recebe o arquivo.
Não tenho experiencia com programação, estou inciando agora… Preciso da ajuda de voces…
Desde já, obrigada pela compreensão.

Por favor, ao postar tópicos, NÃO DEIXE O TÍTULO INTEIRO EM LETRAS MAIÚSCULAS.

se vc tá testando a URI pelo browser, ele vai usar o método GET… vc precisa gerar uma requisição POST, por exemplo criando um html com um form method=post, ou usando uma ferramenta como o plugin POSTER do firefox ou do chrome.

ah sim… eu estava pesquisando aqui… e para receber um metodo post… tem que criar um metodo doPost no service do servlet. Como que faz isso? Nao entendi… e precisa fazer mesmo isso?

vc precisa fazer isso se vc for usar sevlets para o serviço REST… vc tá usando JAX-WS, é diferente…

teoricamente a classe que vc fez, com o @POST já funcionaria, vc só tem que configurar direitinho o JAX-WS… não vou conseguir te ajudar muito com isso.

Fazer com VRaptor é mais fácil :wink: