Marcks1
Marcks1

Reputation: 15

HttpPut on Android not working

I'm trying to send an image from an Android app to a Java application using WebServices.

On the server side I have this code and it works fine using Postman as client:

@Path("/report")
public class ReportService {

@PUT
@Path("/put")
@Consumes(MediaType.APPLICATION_JSON)
public Report saveReport(String json){
    return ReportDAO.saveReport(json);
}

On the other hand I have my android application which is trying to upload an image to the server:

 try {
            //Encode the image
            String imagenPath = params[1];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Bitmap myBitmap = BitmapFactory.decodeFile(imagenPath);
            myBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] imageBytes = baos.toByteArray();
            String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

            //Create client,set url and entity
            HttpClient httpClient = new DefaultHttpClient();

            StringEntity entity = new StringEntity(encodedImage);

            HttpPut httpPut = new HttpPut("http://10.0.2.2:8080/xxx/rest/report/put");
            httpPut.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPut);
            HttpEntity resp = response.getEntity();

        }catch(Exception e){
            e.printStackTrace();
        }
}

I'm using Android Studio's virtual device and it's working fine with GET methods but is failing with POST/PUT.

I don't get any exception and the method doesn't even reach the server. When I use EntityUtils to see what is in the response,I get an empty String.

Copying the url and swapping "http://10.0.2.2:8080" to "http://localhost:8080" on Postman is reaching the server but not from my Android application.

Thanks for help!

Upvotes: 0

Views: 197

Answers (2)

Niraj Sanghani
Niraj Sanghani

Reputation: 1493

As you said

Copying the url and swapping "http://10.0.2.2:8080" to "http://localhost:8080" on Postman is reaching the server but not from my Android application.

I assume your webservice is in the same machine as your postman. That is your problem.

You need to create a server that exposes the service to your local network port. Or you need a public IP hosted service.

Your code is fine, it needs to be publicly exposed over the Internet or the Local Network and get the path of Network. Only then it will work.

You cannot find your PC in a different network, can you now? This is the ABC of Client Server Communication and Networking.

Upvotes: 1

afot
afot

Reputation: 21

you have to check that your android studio virtual device and your server are in the same subnet so you have access there.

you have to expose the network from your computer to your virtual device to make it work.

Upvotes: 1

Related Questions