如何获得外部IP成功(How to get external IP successfully)

2019-06-23 23:45发布

看完后: 获得Java中的“外部” IP地址

码:

public static void main(String[] args) throws IOException
{
    URL whatismyip = new URL("http://automation.whatismyip.com/n09230945.asp");
    BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));

    String ip = in.readLine(); //you get the IP as a String
    System.out.println(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)
at java.net.URL.openStream(Unknown Source)
at getIP.main(getIP.java:12)

我想这是因为服务器响应心不是足够快,反正是有保证它会得到外部IP?

编辑:好了,所以它的被拒,其他网站的任何人都知道,可以做同样的功能

Answer 1:

在您运行下面的代码来看看这个: http://www.whatismyip.com/faq/automation.asp

public static void main(String[] args) throws Exception {

    URL whatismyip = new URL("http://automation.whatismyip.com/n09230945.asp");
    URLConnection connection = whatismyip.openConnection();
    connection.addRequestProperty("Protocol", "Http/1.1");
    connection.addRequestProperty("Connection", "keep-alive");
    connection.addRequestProperty("Keep-Alive", "1000");
    connection.addRequestProperty("User-Agent", "Web-Agent");

    BufferedReader in = 
        new BufferedReader(new InputStreamReader(connection.getInputStream()));

    String ip = in.readLine(); //you get the IP as a String
    System.out.println(ip);
}


Answer 2:

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


Answer 3:

虽然与去打打我看到你的问题。 我做了一个快速应用程序在谷歌App Engine的使用转到:

打这个网址:

http://agentgatech.appspot.com/

Java代码:

new BufferedReader(new InputStreamReader(new URL('http://agentgatech.appspot.com').openStream())).readLine()

进入代码,你可以复制,使自己的应用程序应用程序:

package hello

import (
    "fmt"
    "net/http"
)

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

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


Answer 4:

403响应表示服务器明确拒绝你因为某些原因请求。 联系WhatIsMyIP对细节的操作。



Answer 5:

有些服务器具有触发阻止“非浏览器”访问。 他们明白,你是某种自动应用程序,可以做一个DOS攻击 。 为了避免这种情况,你可以尝试使用一个lib访问资源,并设置了“浏览器”标题。

wget的工作在这个方式 :

 wget  -r -p -U Mozilla http://www.site.com/resource.html

使用Java,您可以使用HttpClient的LIB ,并设置“用户代理”标头。 看看节“试一试”的主题5。

希望这可以帮到你。



Answer 6:

我们已经建立CloudFlare和设计他们挑战陌生useragents。 如果你可以设置你的UA共同的东西,你应该能够获得访问权限。



Answer 7:

您可以使用像这样的另一个Web服务; http://freegeoip.net/static/index.html



Answer 8:

使用AWS上检查IP地址链接me.Please记工作是MalformedURLException的,IOException异常将被添加,以及

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


Answer 9:

这就是我如何与rxJava2和Butterknife做到这一点。 你会想在另一个线程运行的网络代码,因为你会得到一个异常的主线程上运行的网络代码! 我用rxJava代替的AsyncTask因为rxJava清理很好当用户线程完成之前移动到下一个UI。 (这是超级有用的非常繁忙的UI的)

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

更新 -我发现的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;
}


文章来源: How to get external IP successfully
标签: java ip