HttpClient添加依赖

首先在build.gradle中声明使用

android {
//声明 使用
	useLibrary 'org.apache.http.legacy'
}
dependencies {
//依赖
  implementation 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
}

HttpGet请求

//1.创建 HttpClient
  HttpClient client = HttpClients.createDefault();
//HttpUriRequest
HttpGet get = new HttpGet(url + "?tel=" + phoneNum);

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

  //3.获取结果
  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();
}

HttpPost请求

  //创建HttpClient
      HttpClient client = HttpClients.createDefault();
  //post请求
  HttpPost post = new HttpPost(url);

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

  //请求体
  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();
}

猜你喜欢

转载自blog.csdn.net/xieyu1999/article/details/83657330