java:
public class MainActivity extends AppCompatActivity {
private TextView mText;
private String mIPAddress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView) findViewById(R.id.text);
}
public void click(View view) {
requestIp();
}
private void requestIp() {
String url = "http://2017.ip138.com/ic.asp";
OkGo.get(url).execute(new AbsCallback<byte[]>() {
@Override
public byte[] convertSuccess(Response response) throws Exception {
return new byte[0];
}
@Override
public void onSuccess(byte[] bytes, Call call, Response response) {
try {
//转化为GBK编码,返回结果为html格式
byte[] responseBytes = response.body().bytes();
String responseUrl = new String(responseBytes, "GBK");
Log.v("simon", responseUrl);
mText.setText(responseUrl);
//提取html中需要的部分
List resultList = getContext(responseUrl);
for (Iterator iterator = resultList.iterator(); iterator.hasNext(); ) {
String context = (String) iterator.next();
mText.setText(context);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
/**
* 提取"<title>XXXX</title>"中的文字XXXX
*
* @param html 要解析的html文档内容
* @return 解析结果,可以多次匹配,每次匹配的结果按文档中出现的先后顺序添加进结果List
*/
public static List getContext(String html) {
List resultList = new ArrayList();
Pattern p = Pattern.compile("<center>([^</center>]*)");//匹配<title>开头,</title>结尾的文档
Matcher m = p.matcher(html);//开始编译
while (m.find()) {
resultList.add(m.group(1));//获取被匹配的部分
}
return resultList;
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.simon.ipcheckdemo.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ip地址:"/>
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="获取ip地址"/>
</LinearLayout>
权限:
<uses-permission android:name="android.permission.INTERNET" />
返回的数据为:
结果: