Rescue only the Multipart response body

Asked

Viewed 75 times

1

I am trying to download a JSON file, it is sent to me via Multipart, I can recover it but I don’t want to save it in a physical file, so I am taking the return and converting it into string. My problem is in the conversion because it brings me the multi part headers so I can’t possibly convert it to a json object. Has how I remove these header and stay only with the body of the answer without the need to record the file ?

below is an example of the string response.

--e237ecf6-b3ab-4eb0-b94a-8077a7abb566

Content-Disposition: form-data; name=Lists; filename=Lists

[{"Code company":"1",.........................]

Below is the method I’m using.

public static JSONObject downloadMultiPart(String url) throws JSONException {
    JSONObject resposta = new JSONObject();
    String respws;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        Log.i("HDEBUG","Download de JSON - URL ["+url+"]");
         
        HttpURLConnection con = (HttpURLConnection) ( new URL(url)).openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(30000); // 30 segundos de time out
        con.setDoInput(true);
        con.setDoOutput(false);
        con.connect();
         
        InputStream is = con.getInputStream();
        byte[] b = new byte[1024];
         
        while ( is.read(b) != -1)
            baos.write(b);
         
        con.disconnect();
        
        respws = new String(baos.toByteArray(),"UTF-8");
        
        Multipart multi = new Multipart(respws);
        String corpo = multi.getSubType();
        
        resposta.put("ok",true);
        resposta.put("resposta", corpo.toString());
    }
    catch(Throwable t) {
        resposta.put("ok",false);
        resposta.put("resposta","");
    }
     
    return resposta;
}

2 answers

1

Guys I redid everything and now it worked, below below the code I hope it will be useful to you.

@SuppressLint("NewApi") public static JSONObject downloadMultiPart(String url) throws JSONException {
    JSONObject resposta = new JSONObject();
    String respws;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        URL urlx = new URL(url);
        URLConnection conection = urlx.openConnection();
        conection.connect();

        InputStream input = new BufferedInputStream(urlx.openStream(),
                8192);

        String caminho = Environment.getExternalStorageDirectory().toString()+"/OsManager.kml";

        try{
            File f = new File (caminho);
            f.delete();
        } catch(Exception e){
            Log.i("HDEBUG","Arquivo ainda não existe.");
        }

       FileOutputStream output = new FileOutputStream(caminho);

        byte data[] = new byte[1024];

        long total = 0;

        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            output.write(data, 0, count);
        }

        output.flush();

        output.close();
        input.close();


        String linha = "";
        BufferedReader arquivo = new BufferedReader(new FileReader(caminho));
        int contador = 0;
        while(arquivo.ready()) {    
            String tmp_linha = arquivo.readLine();
            if(contador == 3)
            {
                linha = tmp_linha;
            }
            contador = contador + 1;
        }
        File filem = new File(caminho);
        filem.delete();

        resposta.put("ok", true);
        resposta.put("resposta", linha);
    }
    catch(Throwable t) {
        resposta.put("ok",false);
        resposta.put("resposta","");
    }

    return resposta;
}

0

Instead of getSubType(), Use the method getBodyParts() to retrieve a list that actually contains the body of the message. The content should be in one of the elements of the list, which actually probably has only one element.

The return of the method will be a BodyPart. The content can be accessed by the method getEntity.

But sometimes the body of a message Multipart is another message Multipart. Then you may have to "descend" another level, that is, the object (entity) returned by getEntity could be another MultiPart.

If in doubt, post a copy of the complete message so it can be analyzed.

  • instead of multi.getSubType(); I would use multi.getBodyPart(); ?

  • @Hiagosouza Yes, but the difference is I wouldn’t return one String.

  • So more here in case I only have the getBodyParts method

  • In fact I believe it is the way in which I am receiving this file, the method I am using is correct to receive Multipart ?

  • @Hiagosouza I just realized we’re talking about different Apis. I rephrased the answer.

  • Didn’t work =/

  • respws = new String(baos.toByteArray(),"UTF-8"); Multipart multi = new Multipart(respws); Bodypart body = (Bodypart) multi.getBodyParts(); Httpentity corpofinal = ((Httpresponse) body). getEntity(); reply.put("ok",true); reply.put("response", corpofinal.getContent());

  • @Hiagosouza "Didn’t work" is very vague. I have already said that without seeing the contents of the message there is no way to be sure of the implementation. The battery of my crystal ball is over. Also, you’re trying to put the answer into a JSON object, but you’re not even checking what the getContent returned. Java will not convert content to Json automatically. It is probably a String and you will have to convert from String to Json.

  • Okay, I meant you didn’t bring me any content. Otherwise it brings the content but with the Multipart information, if I save the file and open it again it works, however it is one more step and as I have a great content take longer. I’ll try again and return to you what happened.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.