Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何成功获取外部IP_Java_Ip - Fatal编程技术网

Java 如何成功获取外部IP

Java 如何成功获取外部IP,java,ip,Java,Ip,阅读后: 代码: 我以为我是个胜利者,但我犯了以下错误 Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://automation.whatismyip.com/n09230945.asp at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)

阅读后:

代码:

我以为我是个胜利者,但我犯了以下错误

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://automation.whatismyip.com/n09230945.asp
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at getIP.main(getIP.java:12)
我认为这是因为服务器的响应速度不够快,是否有办法确保它能够获得外部ip


编辑:好的,那么它被拒绝了,其他任何人都知道另一个站点可以执行相同的功能

403响应表示服务器出于某种原因明确拒绝了您的请求。有关详细信息,请联系WhatIsMyIP的运营商。

您可以使用其他类似的web服务

某些服务器具有阻止“非浏览器”访问的触发器。他们知道你是一种自动应用程序,可以做很多事情。为了避免这种情况,您可以尝试使用lib访问资源并设置“browser”头

wget的工作原理如下:

使用Java,您可以使用和设置“User Agent”头。 查看主题5“尝试的事情”部分


希望这能对您有所帮助。

在运行以下代码之前,请查看以下内容:


在玩围棋的时候,我看到了你的问题。我使用Go在Google App Engine上制作了一个快速应用程序:

点击此URL:

Java代码:

new BufferedReader(new InputStreamReader(new URL('http://agentgatech.appspot.com').openStream())).readLine()
你可以复制并制作自己的应用程序的Go代码:

package hello

import (
    "fmt"
    "net/http"
)

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, r.RemoteAddr)
}

我们已经设置了
CloudFlare
,按照设计,他们正在挑战不熟悉的用户代理。如果您可以将UA设置为普通,您应该能够获得访问权限。

使用AWS上的检查IP地址链接对我来说很有效。请注意,还需要添加MalformedURLException和IOException

    public static void main(String[] args) throws IOException 
    {
    URL connection = new URL("http://checkip.amazonaws.com/");
    URLConnection con = connection.openConnection();
    String str = null;
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    str = reader.readLine();
    System.out.println(str);
     }
public String getPublicIpAddress() throws MalformedURLException,IOException {

    URL connection = new URL("http://checkip.amazonaws.com/");
    URLConnection con = connection.openConnection();
    String str = null;
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    str = reader.readLine();


    return str;
}

这就是我使用rxJava2和Butterknife的方法。您将希望在另一个线程中运行网络代码,因为在主线程上运行网络代码会出现异常! 我使用rxJava而不是AsyncTask,因为当用户在线程完成之前进入下一个UI时,rxJava会很好地清理。(这对于非常繁忙的UI非常有用)

更新-我发现URLConnection真的很糟糕;需要很长时间才能得到结果,实际超时不是很好,等等。下面的代码改进了OKhttp的情况

private String getExternalIp() {
    String externIp = "no connection";
    OkHttpClient client = new OkHttpClient();//should have this as a member variable
    try {
        String url = "http://checkip.amazonaws.com/";
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        ResponseBody responseBody = response.body();
        if (responseBody != null) externIp = responseBody.string();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return externIp;
}

HTTP的403错误代码表示禁止。不过,我可以在我的浏览器中访问该网站,不会有任何问题。可能与服务条款有关:Down-Vote,因为此评论有点过时,从现在起,在该网站上检查ip就不那么容易了。更重要的是,上述评论已不再有效。为我工作而不是URL(“);
    public static void main(String[] args) throws IOException 
    {
    URL connection = new URL("http://checkip.amazonaws.com/");
    URLConnection con = connection.openConnection();
    String str = null;
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    str = reader.readLine();
    System.out.println(str);
     }
public String getPublicIpAddress() throws MalformedURLException,IOException {

    URL connection = new URL("http://checkip.amazonaws.com/");
    URLConnection con = connection.openConnection();
    String str = null;
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    str = reader.readLine();


    return str;
}
public class ConfigurationActivity extends AppCompatActivity {

    // VIEWS
    @BindView(R.id.externalip) TextInputEditText externalIp;//this could be TextView, etc.

    // rxJava - note: I have this line in the base class - for demo purposes it's here
    private CompositeDisposable compositeSubscription = new CompositeDisposable();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_wonderful_layout);

        ButterKnife.bind(this);

        getExternalIpAsync();
    }

    // note: I have this code in the base class - for demo purposes it's here
    @Override
    protected void onStop() {
        super.onStop();
        clearRxSubscriptions();
    }

    // note: I have this code in the base class - for demo purposes it's here
    protected void addRxSubscription(Disposable subscription) {
        if (compositeSubscription != null) compositeSubscription.add(subscription);
    }

    // note: I have this code in the base class - for demo purposes it's here
    private void clearRxSubscriptions() {
        if (compositeSubscription != null) compositeSubscription.clear();
    }

    private void getExternalIpAsync() {
        addRxSubscription(
                Observable.just("")
                        .map(s -> getExternalIp())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe((String ip) -> {
                            if (ip != null) {
                                externalIp.setText(ip);
                            }
                        })
        );
    }

    private String getExternalIp() {
        String externIp = null;
        try {
            URL connection = new URL("http://checkip.amazonaws.com/");
            URLConnection con = connection.openConnection(Proxy.NO_PROXY);
            con.setConnectTimeout(1000);//low value for quicker result (otherwise takes about 20secs)
            con.setReadTimeout(5000);
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            externIp = reader.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return externIp;
    }
}
private String getExternalIp() {
    String externIp = "no connection";
    OkHttpClient client = new OkHttpClient();//should have this as a member variable
    try {
        String url = "http://checkip.amazonaws.com/";
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        ResponseBody responseBody = response.body();
        if (responseBody != null) externIp = responseBody.string();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return externIp;
}