public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
        new AuthScope("localhost", 443), new UsernamePasswordCredentials("username", "password"));
    CloseableHttpClient httpclient =
        HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {
      HttpGet httpget = new HttpGet("https://localhost/protected");

      System.out.println("executing request" + httpget.getRequestLine());
      CloseableHttpResponse response = httpclient.execute(httpget);
      try {
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
          System.out.println("Response content length: " + entity.getContentLength());
        }
        EntityUtils.consume(entity);
      } finally {
        response.close();
      }
    } finally {
      httpclient.close();
    }
  }
  /** HttpClient 4.3 简单入门---HttpGet */
  @Test
  public void test01() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // 创建httpClientBuilder
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); // 创建httpClient
    HttpGet httpGet = new HttpGet(HTTPGETTESTURL);
    logger.info("httpGet.getRequestLine():{}", httpGet.getRequestLine());

    try {
      HttpResponse httpResponse = closeableHttpClient.execute(httpGet); // 执行get请求
      HttpEntity httpEntity = httpResponse.getEntity(); // 获取响应消息实体
      logger.info("响应状态:{}", httpResponse.getStatusLine());
      if (httpEntity != null) {
        logger.info("contentEncoding:{}", httpEntity.getContentEncoding());
        logger.info("response content:{}", EntityUtils.toString(httpEntity));
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        closeableHttpClient.close(); // 关闭流并释放资源
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
 /**
  * GET方式请求url
  *
  * @param url 请求地址
  * @param params 请求参数
  * @return url响应结果,java.lang.String类型。
  * @throws java.net.URISyntaxException 输入的url不合法
  * @throws java.io.IOException
  */
 public String get(String url, List<NameValuePair> params) throws URISyntaxException, IOException {
   // 1. 验证输入url的有效性:url没有有效的host或url为相对路径,则url无效。
   URI uri = (new URIBuilder(url)).build();
   HttpHost httpHost = URIUtils.extractHost(uri);
   if (httpHost == null) {
     throw new IllegalArgumentException("缺少有效的HOST");
   }
   String respText;
   // 2. 创建HttpClient对象
   CloseableHttpClient client = getHttpClient();
   // 3. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
   HttpGet httpGet = new HttpGet(uri);
   if (logger.isDebugEnabled()) {
     logger.debug("executing request: ", httpGet.getRequestLine());
   }
   // 4. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;
   //    对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
   if (params != null && params.size() > 0) {
     httpGet.setURI(
         new URI(
             httpGet.getURI().toString()
                 + "?"
                 + EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8))));
   }
   // 5. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
   respText = execute(client, httpHost, httpGet);
   return respText;
 }
  /** Access http://localhost/ */
  public static String hitRootContext(Logger log, URL url, String serverName) throws Exception {
    HttpGet httpget = new HttpGet(url.toURI());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpget.setHeader("Host", serverName);

    log.info("executing request" + httpget.getRequestLine());
    HttpResponse response = httpclient.execute(httpget);

    int statusCode = response.getStatusLine().getStatusCode();
    Header[] errorHeaders = response.getHeaders("X-Exception");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue(
        "X-Exception(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

    return EntityUtils.toString(response.getEntity());
  }
  public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope("localhost", 80),
            new UsernamePasswordCredentials("username", "password"));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    httpclient.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpHost targetHost = new HttpHost("localhost", 80, "http");

    HttpGet httpget = new HttpGet("/");

    System.out.println("executing request: " + httpget.getRequestLine());
    System.out.println("to target: " + targetHost);

    for (int i = 0; i < 3; i++) {
      HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
      HttpEntity entity = response.getEntity();

      System.out.println("----------------------------------------");
      System.out.println(response.getStatusLine());
      if (entity != null) {
        System.out.println("Response content length: " + entity.getContentLength());
        entity.consumeContent();
      }
    }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
  }
  public static void main(String[] args) throws Exception {

    String httpHost = "sl-olfeo";
    int httpPort = 3129;
    String usr = "******";
    String pss = "admin123";

    String TEST_HOST_URL = "camel.apache.org";

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
      httpclient
          .getCredentialsProvider()
          .setCredentials(
              new AuthScope(httpHost, httpPort), new UsernamePasswordCredentials(usr, pss));

      HttpHost proxy = new HttpHost(httpHost, httpPort);
      httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

      HttpHost targetHost = new HttpHost(TEST_HOST_URL, 80, "http");
      HttpGet httpget = new HttpGet("/");

      System.out.println("executing request: " + httpget.getRequestLine());
      System.out.println("via proxy: " + proxy);
      System.out.println("to target: " + targetHost);

      HttpResponse response = httpclient.execute(targetHost, httpget);
      HttpEntity entity = response.getEntity();

      System.out.println("----------------------------------------");
      System.out.println(response.getStatusLine());
      if (entity != null) {
        System.out.println("Response content length: " + entity.getContentLength());
      }
      EntityUtils.consume(entity);

    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpclient.getConnectionManager().shutdown();
    }
  }
Exemple #7
0
  private String forecastIoFor(String latitude, String longitude) throws IOException {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
      HttpGet httpget = new HttpGet(format(getForecastIoUrl() + "/%s,%s", latitude, longitude));
      httpget.addHeader("accept-encoding", "identity");
      System.out.println("Executing request " + httpget.getRequestLine());

      ResponseHandler<String> responseHandler =
          response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
              HttpEntity entity = response.getEntity();
              return entity != null ? EntityUtils.toString(entity) : null;
            } else {
              throw new ClientProtocolException("Unexpected response status: " + status);
            }
          };
      String responseBody = httpclient.execute(httpget, responseHandler);
      System.out.println("----------------------------------------");
      System.out.println(responseBody);
      return responseBody;
    }
  }
  @Test
  public void test03() {
    HttpClient httpClient = buildHttpClient();
    HttpGet httpGet = new HttpGet(HTTPGETTESTURL);
    logger.info("httpGet.getRequestLine():{}", httpGet.getRequestLine());

    try {
      HttpResponse httpResponse = httpClient.execute(httpGet); // 执行get请求
      HttpEntity httpEntity = httpResponse.getEntity(); // 获取响应消息实体
      logger.info("响应状态:{}", httpResponse.getStatusLine());
      if (httpEntity != null) {
        logger.info("contentEncoding:{}", httpEntity.getContentEncoding());
        logger.info("response content:{}", EntityUtils.toString(httpEntity));
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {

    }
  }
  /**
   * Execute a management operation against the JBoss server via HTTP, and perform authentication as
   * needed. The response is then returned to the caller
   *
   * @param urlCmd URL for management command, including parameters, but excluding schema, host and
   *     port number
   * @return JSONObject containing the response
   */
  public JSONObject executeOp(String urlCmd) {
    logger.debug("Executing command " + urlCmd);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
      httpclient
          .getCredentialsProvider()
          .setCredentials(
              new AuthScope(host, port), new UsernamePasswordCredentials(userName, password));

      URL url = new URL("http", host, port, urlCmd);
      logger.debug("Command URL is:" + url);

      HttpGet httpget = new HttpGet(url.toString());

      logger.debug("executing request" + httpget.getRequestLine());
      HttpResponse response = httpclient.execute(httpget);
      HttpEntity entity = response.getEntity();

      if (entity == null) {
        logger.error("Http response did not contain an entity");
      }
      BufferedReader is = new BufferedReader(new InputStreamReader(entity.getContent()));
      String line;
      StringBuffer buff = new StringBuffer();
      while ((line = is.readLine()) != null) {
        buff.append(line);
      }

      JSONObject jsonResp = new JSONObject(buff.toString());

      EntityUtils.consume(entity);

      return jsonResp;
    } catch (Exception e) {
      throw new MonitorException("Management operation failed", e);
    } finally {
      httpclient.getConnectionManager().shutdown();
    }
  }
  public static String getResponse(String scheme, String host, String path, String query)
      throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
      // setProxyDetails();
      /*httpclient.getCredentialsProvider().setCredentials(
              new AuthScope(proxyserver, proxyport),
              new UsernamePasswordCredentials(proxyuser, proxypass));

      HttpHost proxy = new HttpHost(proxyserver, proxyport);

      httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      */
      URI uri = null;

      try {
        uri = new URI(scheme, host, path, query, null);
      } catch (URISyntaxException ex) {
        Logger.getLogger(FetchURL.class.getName()).log(Level.SEVERE, null, ex);
        return "";
      }

      HttpGet httpget = new HttpGet(uri.toASCIIString());

      System.out.println("executing request: " + httpget.getRequestLine());
      // System.out.println("via proxy: " + proxy);

      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String responseBody = httpclient.execute(httpget, responseHandler);
      return responseBody;
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpclient.getConnectionManager().shutdown();
    }
  }
  private String login(int... ids) {
    Log.d(TAG, "login(ids... method start");
    String result = "";
    String result2 = "";
    ArrayList<RecipeGeneral> recipes = null;
    try {
      DefaultHttpClient httpclient = new DefaultHttpClient();
      HttpGet httpget = new HttpGet(Constants.URL_LOGIN);
      httpget.setHeader("Accept", "application/json");

      HttpResponse response = httpclient.execute(httpget);
      HttpEntity entity = response.getEntity();
      Log.d(TAG, "Login form get: " + response.getStatusLine());
      Log.d(TAG, "Entity: " + entity.toString());
      if (entity != null) {
        result = HttpFactory.convertStreamToString(entity.getContent());
        Log.d(TAG, "Result: " + result);
      }

      List<Cookie> cookies = httpclient.getCookieStore().getCookies();
      if (cookies.isEmpty()) {
        Log.d(TAG, "No cookies");
      } else {
        for (int i = 0; i < cookies.size(); i++) {
          Log.d(TAG, "Cookies: " + cookies.get(i).toString());
        }
      }

      JSONObject jsonResponse = new JSONObject(result.trim());
      Log.d(TAG, "jsonResponce: " + jsonResponse.toString());
      String token_value = jsonResponse.getString("token_value");
      String token_name = jsonResponse.getString("token_name");
      Log.d(TAG, "token_value: " + token_value);
      Log.d(TAG, "token_name: " + token_name);

      HttpPost httpost = new HttpPost(Constants.URL_LOGIN);
      httpost.setHeader("Accept", "application/json");

      List<NameValuePair> nvps = new ArrayList<NameValuePair>();
      nvps.add(new BasicNameValuePair("user[email]", login));
      nvps.add(new BasicNameValuePair("user[password]", password));
      nvps.add(new BasicNameValuePair(token_name, token_value));

      httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

      HttpResponse response1 = httpclient.execute(httpost);
      HttpEntity entity1 = response1.getEntity();

      Log.d(TAG, "Login form post: " + response1.getStatusLine());
      if (entity1 != null) {
        result = HttpFactory.convertStreamToString(entity1.getContent());
        Log.d(TAG, "Entity: " + result);
      }

      StringBuilder idsParams = new StringBuilder();
      for (int id : ids) {
        idsParams.append("&ids[]=" + id);
      }
      HttpGet httpget2 = new HttpGet(Constants.URL_SYNC + "?ids[]=0" + idsParams);
      httpget2.setHeader("Accept", "application/json");
      Log.d(TAG, "Request line: " + httpget2.getRequestLine());
      Log.d(TAG, "Request params: " + httpget2.getParams());
      Log.d(TAG, "Request uri: " + httpget2.getURI());

      HttpResponse response2 = httpclient.execute(httpget2);
      HttpEntity entity2 = response2.getEntity();

      Log.d(TAG, "Login form get2: " + response2.getStatusLine());
      Log.d(TAG, "Entity2: " + entity2.toString());

      if (entity2 != null) {
        result2 = HttpFactory.convertStreamToString(entity2.getContent());
        Log.d(TAG, "Result2: " + result2);
      }

      List<Cookie> cookies2 = httpclient.getCookieStore().getCookies();
      if (cookies2.isEmpty()) {
        Log.d(TAG, "No cookies2 ");
      } else {
        for (int i = 0; i < cookies2.size(); i++) {
          Log.d(TAG, "Cookies2 : " + cookies2.get(i).toString());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      receiver.send(Constants.AUTHORIZATION_NOT_PASSED, null);
    }
    return result2;
  }
 /** HttpClient连接SSL */
 public void ssl() {
   CloseableHttpClient httpclient = null;
   try {
     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
     FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
     try {
       // 加载keyStore d:\\tomcat.keystore
       trustStore.load(instream, "123456".toCharArray());
     } catch (CertificateException e) {
       e.printStackTrace();
     } finally {
       try {
         instream.close();
       } catch (Exception ignore) {
       }
     }
     // 相信自己的CA和所有自签名的证书
     SSLContext sslcontext =
         SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
     // 只允许使用TLSv1协议
     SSLConnectionSocketFactory sslsf =
         new SSLConnectionSocketFactory(
             sslcontext,
             new String[] {"TLSv1"},
             null,
             SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
     httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
     // 创建http请求(get方式)
     HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
     System.out.println("executing request" + httpget.getRequestLine());
     CloseableHttpResponse response = httpclient.execute(httpget);
     try {
       HttpEntity entity = response.getEntity();
       System.out.println("----------------------------------------");
       System.out.println(response.getStatusLine());
       if (entity != null) {
         System.out.println("Response content length: " + entity.getContentLength());
         System.out.println(EntityUtils.toString(entity));
         EntityUtils.consume(entity);
       }
     } finally {
       response.close();
     }
   } catch (ParseException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (KeyManagementException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (KeyStoreException e) {
     e.printStackTrace();
   } finally {
     if (httpclient != null) {
       try {
         httpclient.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
 private Address getFromCache(HttpGet request) {
   return cache.get(request.getRequestLine().getUri());
 }
 private Address cacheAddress(HttpGet request, Address address) {
   cache.putIfAbsent(request.getRequestLine().getUri(), address);
   return address;
 }