繁体   English   中英

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

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

我知道还有其他类似的帖子,但没有帮助。

我的代码在模拟器中运行,但是在设备上却出现异常: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时,仅在设备上出现异常。

尝试使用:

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

完成后,在调试器中查找uri对象。 检查它是否有效。 祝好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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