简体   繁体   中英

android http request doesn't work on device, in emulator works

I know there was an other post like this but it doesn't help.

My Code is working in an emulator but on the device I get an Exception: java.lang.IllegalArgumentException: Host name may not be null

Permissions are set:

<uses-permission android:name="android.permission.INTERNET" />

And here is the code:

package com.example.testapp;

import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;

public class mainAct extends Activity {

    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        ARequestTask task = new ARequestTask();

        task.execute(new String[] {});

    }

    class ARequestTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {

            String hallo = "test";
            Log.d("EMAIL", hallo);

            try {
                HttpClient client = new DefaultHttpClient();
                URI uri = new URI("http://.../android/index.php");
                HttpGet get = new HttpGet(uri);

                HttpResponse responseGET = client.execute(get);
                HttpEntity resEntity = responseGET.getEntity();

                if (resEntity != null) {
                    Log.i("RESPONSE", EntityUtils.toString(resEntity));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;

        }

        @Override
        protected void onPostExecute(String result) {
            // use the result as you wish
        }
    }

}

Every time the HttpGet will be executed the Exception comes up BUT only on the device .

Try using:

URI uri = URI.parse("http://.../android/index.php");

After you do that look in the uri object in the debugger. check if it is valid. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM