Enviar imagem para um web service-Android
30/03/2016
0
Ola galera, estou a um ano tentando fazer meu TCC mas estou com problemas ao enviar uma imagem para um web service por Json via post, depois de muito tempo consegui enviar pequenas Strings , mas quando passo a imagem para base 64 so chega null no web service...
Abaixo minha Main
private static final int CAMERA_REQUEST = 1888;
private ImageView recuperaImagem;
private Button btEnviar;
private Button btCamera;
private String temporario;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btEnviar = (Button) findViewById(R.id.btEnviar);
btEnviar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "Aguarde", "Enviando Dados, Por Favor Aguarde...");
try {
JsonSet jsonSet = new JsonSet(getApplicationContext(),"http://192.168.56.1:8080/Web/webresources/webservice/nome",dialog);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
//******************************** camera **************************************************
btCamera = (Button) findViewById(id.btCamera);
recuperaImagem=(ImageView) findViewById(id.recuperaImagem);
btCamera.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
recuperaImagem.setImageBitmap(photo);
Dados dados = new Dados();
String imgString = BitMapToString(photo);
dados.setImagem(photo);
}
}
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.WEBP, 100, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.NO_WRAP);
return temp;
}
abaixo a classe responsavel pelo envio
public class JsonSet extends Activity{
private String url;
private ProgressDialog dialog;
private String parametro;
private Thread thread = null;
private Context context = null;
private String erro = "Nenhum";
String resultado= null;
public JsonSet(Context context, String url, ProgressDialog dialog) throws UnsupportedEncodingException {
this.dialog = dialog;
this.context = context;
this.url = url;
new SetCobranca().execute();
}
private class SetCobranca extends AsyncTask<String, String, String> {
protected void onPostExecute(String result){ // String result
if (dialog != null){
dialog.dismiss();
}
try {
if (result.equalsIgnoreCase("Erro")) {
Toast toast = Toast.makeText(context, "Erro ao enviar post.", Toast.LENGTH_LONG);
toast.show();
} else if (result.equalsIgnoreCase("Nenhum")) {
Toast toast = Toast.makeText(context, "Nenhum post para ser enviado", Toast.LENGTH_LONG);
toast.show();
} else {
Toast toast = Toast.makeText(context, "Akuma "+resultado, Toast.LENGTH_LONG);
toast.show();
}
}catch (Exception e){
System.out.println("erro aqui: "+ e.getMessage());
}
}
@Override
protected String doInBackground(String... params) {
JSONArray jsonArray = new JSONArray();
try {
//jsonArray.put("teste");
Dados dados = new Dados();
Gson g = new Gson();
JsonObject foto = new JsonObject();
String json = g.toJson(dados);// converte o objeto em json
jsonArray.put(dados.getImagem());
} catch (Exception e) {
//System.out.println(e.getMessage());
e.printStackTrace();
}
String result = null;
if (jsonArray.length() > 0) {
try {
URL urlCon = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlCon.openConnection();
conn.setConnectTimeout(50000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonArray.toString());
writer.flush();
writer.close();
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
resultado = result; // recebe o resultado do web service
erro = "Sucesso";
} catch (Exception e){
//System.out.println("Erro: "+ e.getMessage());
erro = "Erro";
e.printStackTrace();
} catch (ExceptionInInitializerError ex){
erro = "Erro";
ex.printStackTrace();
}
}else{
erro = "Nenhum";
}
return erro;
}
}
public void PauseThread(){
if (thread != null) {
thread.interrupt();
}
}
}
web service java
@POST
@Consumes("application/json")
@Path("nome")
public String putJson (String nome){
/*
Gson gson = new Gson();
gson.toJson(nome);
*/
System.out.print(nome);
return ("Sucesso"+nome);
Abaixo minha Main
private static final int CAMERA_REQUEST = 1888;
private ImageView recuperaImagem;
private Button btEnviar;
private Button btCamera;
private String temporario;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btEnviar = (Button) findViewById(R.id.btEnviar);
btEnviar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "Aguarde", "Enviando Dados, Por Favor Aguarde...");
try {
JsonSet jsonSet = new JsonSet(getApplicationContext(),"http://192.168.56.1:8080/Web/webresources/webservice/nome",dialog);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
//******************************** camera **************************************************
btCamera = (Button) findViewById(id.btCamera);
recuperaImagem=(ImageView) findViewById(id.recuperaImagem);
btCamera.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
recuperaImagem.setImageBitmap(photo);
Dados dados = new Dados();
String imgString = BitMapToString(photo);
dados.setImagem(photo);
}
}
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.WEBP, 100, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.NO_WRAP);
return temp;
}
abaixo a classe responsavel pelo envio
public class JsonSet extends Activity{
private String url;
private ProgressDialog dialog;
private String parametro;
private Thread thread = null;
private Context context = null;
private String erro = "Nenhum";
String resultado= null;
public JsonSet(Context context, String url, ProgressDialog dialog) throws UnsupportedEncodingException {
this.dialog = dialog;
this.context = context;
this.url = url;
new SetCobranca().execute();
}
private class SetCobranca extends AsyncTask<String, String, String> {
protected void onPostExecute(String result){ // String result
if (dialog != null){
dialog.dismiss();
}
try {
if (result.equalsIgnoreCase("Erro")) {
Toast toast = Toast.makeText(context, "Erro ao enviar post.", Toast.LENGTH_LONG);
toast.show();
} else if (result.equalsIgnoreCase("Nenhum")) {
Toast toast = Toast.makeText(context, "Nenhum post para ser enviado", Toast.LENGTH_LONG);
toast.show();
} else {
Toast toast = Toast.makeText(context, "Akuma "+resultado, Toast.LENGTH_LONG);
toast.show();
}
}catch (Exception e){
System.out.println("erro aqui: "+ e.getMessage());
}
}
@Override
protected String doInBackground(String... params) {
JSONArray jsonArray = new JSONArray();
try {
//jsonArray.put("teste");
Dados dados = new Dados();
Gson g = new Gson();
JsonObject foto = new JsonObject();
String json = g.toJson(dados);// converte o objeto em json
jsonArray.put(dados.getImagem());
} catch (Exception e) {
//System.out.println(e.getMessage());
e.printStackTrace();
}
String result = null;
if (jsonArray.length() > 0) {
try {
URL urlCon = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlCon.openConnection();
conn.setConnectTimeout(50000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonArray.toString());
writer.flush();
writer.close();
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
resultado = result; // recebe o resultado do web service
erro = "Sucesso";
} catch (Exception e){
//System.out.println("Erro: "+ e.getMessage());
erro = "Erro";
e.printStackTrace();
} catch (ExceptionInInitializerError ex){
erro = "Erro";
ex.printStackTrace();
}
}else{
erro = "Nenhum";
}
return erro;
}
}
public void PauseThread(){
if (thread != null) {
thread.interrupt();
}
}
}
web service java
@POST
@Consumes("application/json")
@Path("nome")
public String putJson (String nome){
/*
Gson gson = new Gson();
gson.toJson(nome);
*/
System.out.print(nome);
return ("Sucesso"+nome);
Jhonatan Constancio
Curtir tópico
+ 0
Responder
Clique aqui para fazer login e interagir na Comunidade :)