android http请求在设备上不起作用,在模拟器中工作

时间:2012-11-14 08:06:01

标签: android request

我知道还有其他这样的帖子,但它无济于事。

我的代码在模拟器中工作,但在设备上我得到一个例外: java.lang.IllegalArgumentException:主机名可能不为null

设置了权限:

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

以下是代码:

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
        }
    }

}

每次执行HttpGet时,Exception都会出现但仅在设备上出现。

1 个答案:

答案 0 :(得分:0)

尝试使用:

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

执行此操作后,查看调试器中的uri对象。检查它是否有效。 祝你好运。