根據IP地址定位城市
阿新 • • 發佈:2018-11-12
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" />
返回的資料為:
結果: