HttpClient网络请求数据获取电话号码信息
程序员文章站
2022-06-24 23:51:01
...
build.gradle 注入依赖,声明
android {
compileSdkVersion 27
//声明 使用
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "bw.com.day3_3"
minSdkVersion 19
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//依赖
implementation 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
}
activity中的代码
private EditText editText;
private Button button;
private TextView textView;
private final int UPDATE_UI=1;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case UPDATE_UI:
textView.setText(msg.obj.toString());
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
button = findViewById(R.id.button);
textView = findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(
new Runnable() {
@Override
public void run() {
getInfo(editText.getText().toString());
}
}
).start();
}
});
}
private String path="http://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
public void getInfo(String photoNum){
//请求配置:连接超时
RequestConfig requestConfig=RequestConfig
.custom()
.setConnectTimeout(5000)
.build();
//创建httpclient
CloseableHttpClient client =HttpClients
.custom()
.setDefaultRequestConfig(requestConfig)
.build();
//创建请求对象
HttpUriRequest request=RequestBuilder
.get() //请求方法
.setUri(path) //请求url
.addParameter("tel",photoNum)//请求参数
.build();
//执行一个请求
try {
HttpResponse response=client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode==200){
String result = EntityUtils.toString(response.getEntity());
Message message = handler.obtainMessage(UPDATE_UI, result);
handler.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}