private EditText editText;
private Button insert;
private TextView textView;
private final int UPDATE = 1;
private StringBuilder stringBuilder;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case UPDATE:
textView.setText(msg.obj.toString());
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.phone);
insert = findViewById(R.id.insert);
textView = findViewById(R.id.textView);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
//Log.i("TAG", "线程");
insertNumber(editText.getText().toString());
}
}).start();
}
});
}
private String path = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=";
//获取数据
private void insertNumber(String number){
try {
URL url = new URL(path + number);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200){
String result = stream(urlConnection.getInputStream());
Message message = handler.obtainMessage(UPDATE, result);
handler.sendMessage(message);
}else {
Message message = handler.obtainMessage(UPDATE, responseCode);
handler.sendMessage(message);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//将字节转为字符
private String stream(InputStream is) {
try {
InputStreamReader isr = new InputStreamReader(is, "GBK");
BufferedReader br = new BufferedReader(isr);
stringBuilder = new StringBuilder();
for (String temp = br.readLine(); temp != null; temp = br.readLine()) {
stringBuilder.append(temp);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
HttpUrlContent号码
最新推荐文章于 2023-06-05 15:50:41 发布