/**
   * 发送POST请求
   *
   * @param url 网络请求地址
   * @param nvps 请求参数列表
   * @return
   */
  public String post(String url, List<NameValuePair> nvps) {
    HttpPost request = new HttpPost(url);
    CloseableHttpResponse response = null;
    try {
      request.setEntity(new UrlEncodedFormEntity(nvps)); // 封装post请求参数
      response = client.execute(request); // 发送请求
      int resultCode = response.getStatusLine().getStatusCode(); // 返回响应状态

      /** ************** 网络异常, 退出程序 ************* */
      if (HttpStatus.SC_OK != resultCode) return EMPTY;

      /** ************** 将响应转换为字符串 ************* */
      HttpEntity entity = response.getEntity();
      return EntityUtils.toString(entity, UTF_8);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (null != request && !request.isAborted()) {
        request.abort();
      }
      HttpClientUtils.closeQuietly(client);
      HttpClientUtils.closeQuietly(response);
    }
    return EMPTY;
  }
Example #2
0
  protected String executePostRequest(String url, String request) {
    HttpPost httpPost = null;

    try {
      prepareRequest();
      httpPost = new HttpPost(url);
      if (DEBUG) Log.d(getName(), "Http request : " + request);
      httpPost.setEntity(new StringEntity(request));
      return executeRequest(httpPost);
    } catch (UnsupportedEncodingException e) {
      Log.e(getName(), "Cannot build the HTTP POST : " + e);
      return "";
    } finally {
      if (request != null && !httpPost.isAborted()) {
        httpPost.abort();
      }
    }
  }