欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

项目咨询——用HttpClient查询电话号码归属地

程序员文章站 2022-05-19 12:29:24
...

**

第一种方法

**
public class MainActivity extends AppCompatActivity {
private EditText input;
private TextView info;

private final int UPDATE_UI = 1;

@SuppressLint(“HandlerLeak”) private Handler mHandler = new Handler() {
@Override public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_UI:
info.setText(msg.obj.toString());
break;
}
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

input = findViewById(R.id.input);
info = findViewById(R.id.info);

findViewById(R.id.query).setOnClickListener(new View.OnClickListener() {
  @Override public void onClick(View v) {
    new Thread(
        new Runnable() {
          @Override public void run() {
            //在build.gradle中声明使用
            //添加依赖
            //getRequestData(input.getText().toString());
            postRequestData(input.getText().toString());
          }
        }
    ).start();
  }
});

}

private String url = “http://tcc.taobao.com/cc/json/mobile_tel_segment.htm”;

private void getRequestData(String phoneNum) {
//1 创建 HttpClient
HttpClient client = HttpClients.createDefault();

//HttpUriRequest
HttpGet get = new HttpGet(url + "?tel=" + phoneNum);

try {
  //shift f6 重构
  //执行请求
  HttpResponse response = client.execute(get);

  //获取结果
  int statusCode = response.getStatusLine().getStatusCode();
  if (statusCode == 200) {
    String result = EntityUtils.toString(response.getEntity());
    mHandler.sendMessage(mHandler.obtainMessage(UPDATE_UI, result));
  }
} catch (IOException e) {
  e.printStackTrace();
}

}

private void postRequestData(String phoneNum) {
try {
//创建HttpClient
HttpClient client = HttpClients.createDefault();

  //post请求
  HttpPost post = new HttpPost(url);

  // 构建请求参数
  List<NameValuePair> params = new ArrayList<>();
  params.add(new BasicNameValuePair("tel", phoneNum));

  //请求体    UrlEncodedFormEntity
  post.setEntity(new UrlEncodedFormEntity(params));

  //执行请求
  HttpResponse response = client.execute(post);

  //获取结果
  int statusCode = response.getStatusLine().getStatusCode();
  if (statusCode == 200) {
    //////////////////////////////////////////////////////////
    String result = EntityUtils.toString(response.getEntity());
    mHandler.sendMessage(mHandler.obtainMessage(UPDATE_UI, result));
  }
} catch (UnsupportedEncodingException e) {
  e.printStackTrace();
} catch (ClientProtocolException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

}
}

**

第二种方法

**
public class DemoActivity extends AppCompatActivity {

private EditText input;
private TextView info;

private final int UPDATE_UI = 1;

@SuppressLint(“HandlerLeak”) private Handler mHandler = new Handler() {
@Override public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_UI:
info.setText(msg.obj.toString());
break;
}
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

input = findViewById(R.id.input);
info = findViewById(R.id.info);

findViewById(R.id.query).setOnClickListener(new View.OnClickListener() {
  @Override public void onClick(View v) {
    new Thread(
        new Runnable() {
          @Override public void run() {
            //在build.gradle中声明使用
            //添加依赖
            requestData(input.getText().toString());
          }
        }
    ).start();
  }
});

}

private String url = “http://tcc.taobao.com/cc/json/mobile_tel_segment.htm”;

private void requestData(String phoneNum) {
try {
//请求配置:连接超时
RequestConfig requestConfig = RequestConfig
.custom()
.setConnectTimeout(5000)
.build();
//创建httpclient
//HttpClient client = HttpClients.createDefault();
CloseableHttpClient client = HttpClients
.custom()
.setDefaultRequestConfig(requestConfig)
.build();

  //构建请求对象
  HttpUriRequest request = RequestBuilder
      //请求方法
      .get()
      //.post()
      //请求url
      .setUri(url)
      //请求参数
      .addParameter("tel", phoneNum)
      .build();

  //执行一个请求
  HttpResponse response = client.execute(request);
  int statusCode = response.getStatusLine().getStatusCode();
  if (statusCode == 200) {
    String result = EntityUtils.toString(response.getEntity());
    mHandler.sendMessage(mHandler.obtainMessage(UPDATE_UI, result));
  }
} catch (IOException e) {
  e.printStackTrace();
}

}
}