Search code examples
androidpostmultipart

HttpEntity target host must not be null


I'm trying to do a POST from my android Virtual Machine to a web API that is running on my development host. I can do a GET request and a "normal" JSON POST but when i try to do it as a MultiPart it's getting tricky.

After some research I found a good answer from Muhammad Babar Post multipart request with Android SDK. Which helped with the HTTP Entity.

So, the error :
java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=http://10.0.2.2:53918/api/Problems

It happens when the code gets to the:

HttpResponse response = client.execute(post);

My code:

public class MainActivity extends Activity {
    private DefaultHttpClient mHttpClient;
    private String result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void ServerCommunication(View view) {
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        mHttpClient = new DefaultHttpClient(params);
        uploadUserPhoto();
    }



    public void uploadUserPhoto() {
        try{
            String uri = URLEncoder.encode( "http://10.0.2.2:53918/api/Problems","UTF-8");
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(uri);


            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            entityBuilder.addTextBody("Id", "7");
            entityBuilder.addTextBody("DateReported", "22/04/2015");
            entityBuilder.addTextBody("Category", "C");

            HttpEntity entity = entityBuilder.build();
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            HttpEntity httpEntity = response.getEntity();
            result = EntityUtils.toString(httpEntity);
            Log.v("result", result);
        }

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



    }

Please help me resolve the IllegalStateException above.


Solution

  • The URLEncoder is meant to encode query parameters not to create a URI with scheme, host, and port. Instead move the URI to the constructor of the HttpPost for example new HttpPost("http://10.0.2.2").

    Also, this API was deprecated at API Level 22, please see the documentation for the newer alternative API.