现在的位置: 首页 > 综合 > 正文

HttpClient模拟发送http请求

2018年04月28日 ⁄ 综合 ⁄ 共 806字 ⁄ 字号 评论关闭

public static void post() throws Exception {
  HttpClient _httpClient = new DefaultHttpClient();
  HttpPost post = new HttpPost("uri");
  HttpEntity result = null;
  BasicNameValuePair basicNameValuePair = new BasicNameValuePair("name", "value");
  List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
  nameValuePairs.add(basicNameValuePair);
  try {
   UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
   post.setEntity(entity);
   HttpResponse response = _httpClient.execute(post);
   org.apache.http.StatusLine statusLine = response.getStatusLine();
   if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
    System.out.println("error");
   } else {
    System.out.println("OK");
   }

  } finally {
   if (result != null) {
    try {
     EntityUtils.consume(result);
    } catch (IOException e) {

    }
   }
   post.abort();
  }
 }

抱歉!评论已关闭.