@Test
  public void basicAuth() throws Exception {
    setupRealmUser();
    KerberosContainer kdc = startKdc();
    configureSso(kdc, true);

    // I am not able to get the basic auth to work in FF 45.3.0, so using HttpClient instead
    // org.openqa.selenium.UnsupportedCommandException: Unrecognized command: POST
    // /session/466a800f-eaf8-40cf-a9e8-815f5a6e3c32/alert/credentials
    // alert.setCredentials(new UserAndPassword("user", "ATH"));

    CloseableHttpClient httpClient = getBadassHttpClient();

    // No credentials provided
    assertUnauthenticatedRequestIsRejected(httpClient);

    // Correct credentials provided
    HttpGet get = new HttpGet(jenkins.url.toExternalForm() + "/whoAmI");
    get.setHeader("Authorization", "Basic " + Base64.encode("user:ATH".getBytes()));
    CloseableHttpResponse response = httpClient.execute(get);
    String phrase = response.getStatusLine().getReasonPhrase();
    String out = IOUtils.toString(response.getEntity().getContent());
    assertThat(phrase + ": " + out, out, containsString("Full Name"));
    assertThat(phrase + ": " + out, out, containsString("Granted Authorities: authenticated"));
    assertEquals(phrase + ": " + out, "OK", phrase);

    // Incorrect credentials provided
    get = new HttpGet(jenkins.url.toExternalForm() + "/whoAmI");
    get.setHeader("Authorization", "Basic " + Base64.encode("user:WRONG_PASSWD".getBytes()));
    response = httpClient.execute(get);
    assertEquals(
        "Invalid password/token for user: user", response.getStatusLine().getReasonPhrase());
  }
  /* create Post Request With Provided Json String */
  private HttpGet createGetRequest(String url) throws UnsupportedEncodingException {
    HttpGet gettRequest = new HttpGet(url);
    gettRequest.setHeader("Accept", "application/json");
    gettRequest.setHeader("Content-type", "application/json; charset=utf-8");

    return gettRequest;
  }
Пример #3
0
  public static String httpGetSSL(final String exist, String database, String android_id)
      throws IOException, HttpHostConnectException, ConnectException {
    String getUrl = "https://" + exist + ":50001/exist/rest/db/calendar/" + android_id + ".xml";
    LogHelper.logV(c, "httpGetSSL: " + getUrl);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    //        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(),
    // 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();
    ClientConnectionManager ccm = new SingleClientConnManager(params, schemeRegistry);

    httpClient =
        new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);
    httpClient.setRedirectHandler(new DefaultRedirectHandler());

    HttpGet get = new HttpGet(getUrl);

    get.setHeader("Location", database + ":50082");
    get.setHeader("Connection", "close");

    HttpResponse response = httpClient.execute(get);

    HttpEntity httpEntity = response.getEntity();

    return EntityUtils.toString(httpEntity);
  }
Пример #4
0
  public static String doGet(String url, Map<String, String> headers, Map<String, String> params) {
    HttpClient client = HttpClients.createDefault();
    HttpGet get = new HttpGet();
    if (headers == null) {
      get.setHeader("Content-Type", "text/html;charset=utf-8");
    } else {
      for (String key : headers.keySet()) {
        get.setHeader(key, headers.get(key));
      }
    }
    StringBuffer buffer = new StringBuffer(url);
    if (params != null) {
      buffer.append("?");
      for (String key : params.keySet()) {
        buffer.append(key).append("=").append(params.get(key)).append("&");
      }
      if (buffer.lastIndexOf("&") != -1) {
        buffer.deleteCharAt(buffer.lastIndexOf("&"));
      }
    }

    try {
      get.setURI(new URI(buffer.toString()));
      HttpResponse response = client.execute(get);
      return httpClientResponse(response);
    } catch (Exception e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    return null;
  }
Пример #5
0
  // taglist
  private StringBuilder requestList(String url) throws HttpException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    get.setHeader("Authorization", "GoogleLogin auth=" + auth);
    get.setHeader("Cookie", "SID=" + sid);
    get.setHeader("accept-encoding", "gzip, deflate");
    HttpResponse response = null;
    response = httpclient.execute(get);
    int result = response.getStatusLine().getStatusCode();
    StringBuilder requestListSB;
    if (result == 200) {
      // //System.out.println(get.getResponseBodyAsString());

      requestListSB = new StringBuilder(EntityUtils.toString(response.getEntity()));

    } else {
      //// System.out.println("xxx:" + String.valueOf(result));

      requestListSB = null;
    }
    get.abort();
    httpclient.getConnectionManager().shutdown();
    httpclient = null;
    return requestListSB;
  }
Пример #6
0
  public void requestToken() throws ParseException, HttpException, IOException {
    if (!this.isGetSidAndAuth) return;
    String url = "https://www.google.com/reader/api/0/token?client=scroll&ck=";

    // HttpClient httpclient = new DefaultHttpClient();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    String timestap = String.valueOf(getTimestamp());
    HttpGet get = new HttpGet(url + timestap);
    get.setHeader("Authorization", "GoogleLogin auth=" + auth);
    get.setHeader("Cookie", "SID=" + sid);
    HttpResponse response = null;
    response = httpclient.execute(get);
    int result = response.getStatusLine().getStatusCode();
    ////// System.out.println(result);
    if (result == 200) {
      // this.token = get.getResponseBodyAsString().substring(2);
      //// System.out.println("2222222222222");
      this.token = EntityUtils.toString(response.getEntity()).substring(2);
      //// System.out.println(this.token);
    }
    // ////System.out.println(this.token);
    get.abort();
    httpclient.getConnectionManager().shutdown();
    httpclient = null;
  }
Пример #7
0
    @Override
    protected Void doInBackground(Void... params) {
      String url = Constants.URL_REGISTER_PUSH + _id + "&provider=ANDROID";
      HttpEntity httpEntity = null;
      HttpClient client = new DefaultHttpClient();
      ServiceHandler sh = new ServiceHandler();
      try {
        client.getConnectionManager().getSchemeRegistry().register(sh.getMockedScheme());
      } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
      HttpGet method = new HttpGet(url);
      method.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
      method.setHeader("Authorization", token.getToken_type() + " " + token.getAccess_token());
      try {
        HttpResponse response = client.execute(method);
        httpEntity = response.getEntity();

      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      return null;
    }
Пример #8
0
  private void requestReadingList() throws HttpException, IOException {
    if (!this.isRight()) return;

    int originalSize = 0;
    if (feed != null) {
      items = feed.getItems();
      originalSize = items.size();
    }
    String url =
        "https://www.google.com/reader/atom/user/-/state/com.google/reading-list?n="
            + String.valueOf(pagenumber * everypage);

    HttpClient httpclient = new DefaultHttpClient();
    getreadinglistmethod = new HttpGet(url);
    getreadinglistmethod.setHeader("Authorization", "GoogleLogin auth=" + auth);
    getreadinglistmethod.setHeader("Cookie", "SID=" + sid);
    getreadinglistmethod.setHeader("accept-encoding", "gzip, deflate");
    HttpResponse response = null;
    response = httpclient.execute(getreadinglistmethod);
    int result = response.getStatusLine().getStatusCode();
    // Log.d("GOOGLE_READER", "load result"+result);
    if (result >= 200 && result <= 299) {

      RssParser rp = new RssParser(response.getEntity().getContent());
      //            //System.out.println("++++++++++");

      //            //System.out.println((rp != null ? 1 : 0));
      rp.parse();
      feed = rp.getFeed();
      try {
        items = feed.getItems();
        if (items.size() == originalSize) {
          throw new NoMoreStatusException();
        }
      } catch (Exception e) {
        e.printStackTrace();
        throw new NoNetworkException(e);
      }

      greaderlistItems = new ArrayList<GreaderListItem>();

      for (RssParser.Item item : items) {
        {
          GreaderListItem greaderlistItem = new GreaderListItem();
          greaderlistItem.setId(item.id);
          greaderlistItem.setTitle(item.title);
          greaderlistItem.setLink(item.link);
          greaderlistItem.setAuthor(item.author);
          greaderlistItems.add(greaderlistItem);
        }
      }
      fromindex = (pagenumber - 1) * everypage;
      pagenumber += 1;
      lastModified = new Date();
      // this.getreadingliststring=getreadinglistmethod.getResponseBodyAsString();
    } else {
      throw new NoNetworkException();
    }
    releaseReadingList(getreadinglistmethod);
  }
  public static String getResponse(String word) {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(URL_PRE_QUERY + word + URL_POST_QUERY);

    // Its a key which we can get when registering with cambridge apis
    request.setHeader(
        "accessKey", "bwzcf97b1Zl3rRqygxjrQdnKXkccyrBp7qn7UvXxwB7HqwoABbnO2lhZ6kSCkMkP");
    request.setHeader("accept", "application/json");

    HttpResponse response;
    // Get the response
    BufferedReader rd;
    try {
      response = client.execute(request);
      rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      String line = new String();
      StringBuffer responseStringBuf = new StringBuffer();
      while ((line = rd.readLine()) != null) {
        // System.out.println(line);
        responseStringBuf.append(line);
      }
      return responseStringBuf.toString();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Пример #10
0
  public static String queryStringForGet(String url) {
    HttpGet request = HttpUtil.getHttpGet(url);

    request.setHeader("Accept", "application/xml;q=0.9,*/*;q=0.8");

    request.setHeader("Accept-Charset", "GB2312,GBK,utf-8;q=0.7,*;q=0.7");
    request.setHeader("Connection", "Keep-Alive");

    String result = null;
    try {
      HttpResponse response = HttpUtil.getHttpResponse(request);

      if (response.getStatusLine().getStatusCode() == 200) {
        result = EntityUtils.toString(response.getEntity());

        return result;
      }

    } catch (ClientProtocolException e) {
      result = "ClientProtocolException";
      return result;

    } catch (IOException e) {
      result = "IOException";
      return result;
    }
    return null;
  }
Пример #11
0
  @Test
  public void checkTestMethod() throws Exception {
    withNewHttpClient(
        (driver, client) -> {
          String var = Long.toHexString(new Date().getTime());

          try {
            String url = formatUrl("/import/test", var);
            HttpGet request = new HttpGet(url);
            request.setHeader("Content-Type", "application/json");
            request.setHeader("Accept", "application/json");
            request.setHeader("RESTEASY_CHOSEN_ACCEPT", "*");

            HttpResponse response = client.execute(request);
            assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

            String result = IOUtils.toString(response.getEntity().getContent()).trim();
            assertThat(result, equalTo(var));
          } catch (Exception e) {
            return new HttpCommandResult(e);
          }

          return new HttpCommandResult();
        });
  }
Пример #12
0
  private JSONObject getJSON(String url) {

    HttpGet httpGet;
    httpGet = new HttpGet(url);
    httpGet.setHeader("Accept", "application/json");
    httpGet.setHeader("Content-type", "application/json");

    return JSONResponse(httpGet, null, false);
  }
  // *****************************************************************************
  // If Id is zero(0) get ContactList using HTTP GET method with
  // multipleContactUrl.
  // If Id is non-zero get Contact using HTTP GET method with
  // singleContactUrl.
  // ContactService will return a Contact[] in either case.
  // If getting a specific Contact, the Contact[] will contain only 1 Contact.
  // *****************************************************************************
  public Contact[] GetContactArray(String Id) {
    List<Contact> contactList = new ArrayList<Contact>();
    Contact[] contactArray = null;
    String idString = "";
    String firstNameString = "";
    String lastNameString = "";
    String emailString = "";
    String urlString = "";

    if (Id == "0") {
      urlString = multipleContactUrl;
    } else {
      urlString = singleContactUrl + Id;
    }

    try {
      HttpGet request = new HttpGet(urlString);
      request.setHeader("Accept", "application/json");
      request.setHeader("Content-type", "application/json");
      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpResponse response = httpClient.execute(request);
      HttpEntity responseEntity = response.getEntity();

      // Read response data into buffer
      char[] buffer = new char[(int) responseEntity.getContentLength()];
      InputStream stream = responseEntity.getContent();
      InputStreamReader reader = new InputStreamReader(stream);
      reader.read(buffer);
      stream.close();

      JSONArray contacts = new JSONArray(new String(buffer));
      try {
        for (int i = 0; i < contacts.length(); i++) {
          JSONObject e = contacts.getJSONObject(i);
          idString = e.getString("Id");
          firstNameString = e.getString("FirstName");
          lastNameString = e.getString("LastName");
          emailString = e.getString("Email");
          contactList.add(new Contact(idString, firstNameString, lastNameString, emailString));
        }
        int contactListSize = contactList.size();
        contactArray = new Contact[contactListSize];
        for (int i = 0; i < contactListSize; i++) {
          contactArray[i] = (Contact) contactList.get(i);
        }
      } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
    }
    return contactArray;
  }
Пример #14
0
  public static void profile() throws Exception {
    String accountUrl = keycloak.getDeployment().getAccountUrl();
    HttpGet get = new HttpGet(accountUrl);
    get.setHeader("Accept", "application/json");
    get.setHeader("Authorization", "Bearer " + keycloak.getTokenString(10, TimeUnit.SECONDS));

    HttpResponse response = keycloak.getDeployment().getClient().execute(get);
    if (response.getStatusLine().getStatusCode() == 200) {
      print(response.getEntity().getContent());
    } else {
      System.out.println(response.getStatusLine().toString());
    }
  }
  private String fetchData(String url) {
    StringBuilder data = new StringBuilder();
    boolean isSuccess = false;
    HttpClient stageClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    RailyatriCookies railyatriCookies = getRailyatriCookies();
    if (railyatriCookies != null) {
      ((DefaultHttpClient) stageClient).setCookieSpecs(railyatriCookies.getCookieSpecRegistry());
      ((DefaultHttpClient) stageClient).setCookieStore(railyatriCookies.getCookieStore());
    }

    httpGet.setHeader("Accept", "application/json");
    httpGet.setHeader(
        "User-Agent",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22");
    httpGet.setHeader("Accept-Encoding", "gzip,deflate,sdch");
    try {
      HttpResponse response = stageClient.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
          data.append(line);
          isSuccess = true;
        }

      } else {
        Log.e(tag, "Failed to access: " + url + ". status code = " + statusCode);
        isSuccess = false;
      }
    } catch (ClientProtocolException clientProtocolException) {
      clientProtocolException.printStackTrace();
      Log.e(tag, clientProtocolException.getMessage());
      isSuccess = false;
    } catch (IOException ioException) {
      ioException.printStackTrace();
      Log.e(tag, ioException.getMessage());
      isSuccess = false;
    }

    if (isSuccess) {
      return data.toString();
    } else {
      return null;
    }
  }
Пример #16
0
  String get(URL url, int timeout) throws IOException {
    String content_type = "text/json";

    HttpGet httpget;
    try {
      httpget = new HttpGet(url.toURI());
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }
    httpget.setHeader(HttpHeaders.CONTENT_TYPE, content_type);
    httpget.setHeader(HttpHeaders.ACCEPT, content_type);

    return execute(httpget, timeout);
  }
Пример #17
0
  private List<Account> retrieveAccounts(DefaultHttpClient httpClient, HttpContext context)
      throws IOException, RetrieverException {
    List<Account> accountList = new ArrayList<Account>();
    HttpGet get = new HttpGet("https://bankservices.rabobank.nl/services/productoverview/v1");
    get.setHeader("Content-Type", "application/xml");
    get.setHeader("Accept", "application/xml");

    HttpResponse response = httpClient.execute(get, context);
    if (response.getStatusLine().getStatusCode() != 200) {
      get.abort();
      throw new RetrieverException(
          "Expected HTTP 200 from " + get.getURI() + ", received " + response.getStatusLine());
    }

    InputStream contentStream = null;
    try {
      HttpEntity entity = response.getEntity();
      contentStream = entity.getContent();
      InputStreamReader isReader = new InputStreamReader(contentStream, "UTF-8");
      BufferedReader reader = new BufferedReader(isReader);

      String line;
      while ((line = reader.readLine()) != null) {
        Matcher m = ACCOUNT_LINE.matcher(line);
        while (m.find()) {
          Locale dutchLocale = new Locale("en", "US");
          NumberFormat numberParser = NumberFormat.getNumberInstance(dutchLocale);
          final String accountName = m.group(1);
          final String accountId =
              "net.phedny.valuemanager.sepa.NL57RABO0000000000"
                  .substring(0, 47 - accountName.length());
          Account account =
              new SimpleAccount(
                  accountId + accountName, accountName, m.group(3), numberParser.parse(m.group(4)));
          accountList.add(account);
        }
      }

      return accountList;
    } catch (ParseException e) {
      e.printStackTrace();
    } finally {
      if (contentStream != null) {
        contentStream.close();
      }
    }
    return null;
  }
  /**
   * Fetches user's e-mail - only public for testing.
   *
   * @param allToks OAuth tokens.
   * @param httpClient The HTTP client.
   */
  public int fetchEmail(final Map<String, String> allToks, final HttpClient httpClient) {
    final String endpoint = "https://www.googleapis.com/oauth2/v1/userinfo";
    final String accessToken = allToks.get("access_token");
    final HttpGet get = new HttpGet(endpoint);
    get.setHeader(HttpHeaders.Names.AUTHORIZATION, "Bearer " + accessToken);

    try {
      log.debug("About to execute get!");
      final HttpResponse response = httpClient.execute(get);
      final StatusLine line = response.getStatusLine();
      log.debug("Got response status: {}", line);
      final HttpEntity entity = response.getEntity();
      final String body = IOUtils.toString(entity.getContent(), "UTF-8");
      EntityUtils.consume(entity);
      log.debug("GOT RESPONSE BODY FOR EMAIL:\n" + body);

      final int code = line.getStatusCode();
      if (code < 200 || code > 299) {
        log.error("OAuth error?\n" + line);
        return code;
      }

      final Profile profile = JsonUtils.OBJECT_MAPPER.readValue(body, Profile.class);
      this.model.setProfile(profile);
      Events.sync(SyncPath.PROFILE, profile);
      // final String email = profile.getEmail();
      // this.model.getSettings().setEmail(email);
      return code;
    } catch (final IOException e) {
      log.warn("Could not connect to Google?", e);
    } finally {
      get.reset();
    }
    return -1;
  }
    @Override
    protected Object doInBackground(Object... params) {
      // TODO Auto-generated method stub

      try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        String website =
            "http://myflickpicks.net/php/db/deleteusermovie.php?UserID="
                + currentUser.getId()
                + "&MovieTitle="
                + params[0].toString().replace(" ", "%20");
        HttpGet httpGet = new HttpGet(website);
        httpGet.setHeader("accept", "application/json");
        HttpResponse response = httpClient.execute(httpGet, localContext);
        // Toast.makeText(getActivity().getApplicationContext(), "Adding",
        // Toast.LENGTH_LONG).show(); // For example
        Log.v("MyDebug", "Door 1");
        Log.v("MyDebug", currentUser.getId());
      } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.v("MyDebug", "Door 2");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.v("MyDebug", "Door 3");
      }
      return null;
    }
  @Test
  public void testKeepAlive() throws Exception {
    String url = httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/pin/a14";

    HttpPut request = new HttpPut(url);
    request.setHeader("Connection", "keep-alive");

    HttpGet getRequest = new HttpGet(url);
    getRequest.setHeader("Connection", "keep-alive");

    for (int i = 0; i < 100; i++) {
      request.setEntity(new StringEntity("[\"" + i + "\"]", ContentType.APPLICATION_JSON));

      try (CloseableHttpResponse response = httpclient.execute(request)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        EntityUtils.consume(response.getEntity());
      }

      try (CloseableHttpResponse response2 = httpclient.execute(getRequest)) {
        assertEquals(200, response2.getStatusLine().getStatusCode());
        List<String> values = consumeJsonPinValues(response2);
        assertEquals(1, values.size());
        assertEquals(String.valueOf(i), values.get(0));
      }
    }
  }
Пример #21
0
  /**
   * Wrapper around a HTTP GET to a REST service
   *
   * @param url
   * @return JSONObject
   */
  static JSONObject performHTTPGet(String url) throws IOException, JSONException {

    HttpClient httpClient = new DefaultHttpClient();
    String encoding =
        new String(
            org.apache.commons.codec.binary.Base64.encodeBase64(
                org.apache.commons.codec.binary.StringUtils.getBytesUtf8(
                    props.getProperty(StringConstants.COMMANDER_USER)
                        + ":"
                        + props.getProperty(StringConstants.COMMANDER_PASSWORD))));
    try {
      HttpGet httpGetRequest = new HttpGet(url);
      httpGetRequest.setHeader("Authorization", "Basic " + encoding);
      HttpResponse httpResponse = httpClient.execute(httpGetRequest);
      if (httpResponse.getStatusLine().getStatusCode() >= 400) {
        throw new RuntimeException(
            "HTTP GET failed with "
                + httpResponse.getStatusLine().getStatusCode()
                + "-"
                + httpResponse.getStatusLine().getReasonPhrase());
      }
      return new JSONObject(EntityUtils.toString(httpResponse.getEntity()));

    } finally {
      httpClient.getConnectionManager().shutdown();
    }
  }
Пример #22
0
 public String get(String url) {
   HttpGet get = new HttpGet(getProtocol() + getHost() + "/" + url);
   get.setHeader("Content-Type", "application/xml");
   get.setHeader(
       "User-Agent",
       "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-us) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16");
   try {
     HttpResponse response = getClient().execute(get);
     verify(response.getStatusLine().getStatusCode());
     return EntityUtils.toString(response.getEntity());
   } catch (IOException e) {
     throw new RuntimeException(e);
   } finally {
     get.releaseConnection();
   }
 }
Пример #23
0
  /**
   * This method retrieves data using HTTP or HTTPS protocol and 'get' method.
   *
   * @param url
   * @return
   */
  protected byte[] httpGet(String url) {

    HttpGet httpRequest = null;
    HttpResponse httpResponse = null;
    try {

      final URI uri = URI.create(url.trim());
      httpRequest = new HttpGet(uri);
      if (contentType != null) {
        httpRequest.setHeader(CONTENT_TYPE, contentType);
      }

      httpResponse = getHttpResponse(httpRequest, url);

      final byte[] returnedBytes = readHttpResponse(url, httpResponse);
      return returnedBytes;
    } finally {
      if (httpRequest != null) {
        httpRequest.releaseConnection();
      }
      if (httpResponse != null) {
        EntityUtils.consumeQuietly(httpResponse.getEntity());
      }
    }
  }
Пример #24
0
  public static String sendGet(String url, String encoding, String ip) {
    HttpClient httpClient = new DefaultHttpClient();

    String content = null;
    try {
      if (url.indexOf("https") != -1) {
        httpClient = wrapClient(httpClient);
      }
      HttpGet httpGet = new HttpGet(url);
      if (ip != null) {
        httpGet.setHeader("X-Forwarded-For", ip);
      }
      // 请求超时
      httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 40000);
      // 读取超时
      httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 40000);
      httpClient.getParams().setParameter(AllClientPNames.STRICT_TRANSFER_ENCODING, encoding);
      HttpResponse response = httpClient.execute(httpGet);
      HttpEntity entity = response.getEntity();
      if (entity != null) {
        // 使用EntityUtils的toString方法,传递默认编码,在EntityUtils中的默认编码是ISO-8859-1
        content = EntityUtils.toString(entity, encoding);
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.error("Get url faild, url: " + url, e);
      content = null;
    } finally {
      httpClient.getConnectionManager().shutdown();
    }
    return content;
  }
 @Test
 public void testGetWithIncorrectHttpHeader() throws Exception {
   URL url = buildURL(true, false, null);
   HttpGet httpget = new HttpGet(url.toURI());
   httpget.setHeader("org.wildfly.useStreamAsResponse", "1");
   readHttpResponse(getHttpClient(url).execute(httpget), 400);
 }
Пример #26
0
  public String executeHttpGet(String URL) throws Exception {
    BufferedReader in = null;
    try {
      HttpClient client = new DefaultHttpClient();
      client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
      HttpGet request = new HttpGet();
      request.setHeader("Content-Type", "text/plain; charset=utf-8");
      request.setURI(new URI(URL));
      HttpResponse response = client.execute(request);
      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

      StringBuffer sb = new StringBuffer("");
      String line = "";

      String NL = System.getProperty("line.separator");
      while ((line = in.readLine()) != null) {
        sb.append(line + NL);
      }
      in.close();
      String page = sb.toString();
      // System.out.println(page);
      return page;
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          Log.d("BBB", e.toString());
        }
      }
    }
  }
Пример #27
0
 /** 扩展卡不可用时直接从网络获取图片 */
 public byte[] httpGetUrlAsByte(String url) {
   try {
     int stateCode;
     HttpGet httpGet = new HttpGet(url);
     httpGet.setHeader(
         "Accept-Language",
         (Locale.getDefault().getLanguage() + "-" + Locale.getDefault().getCountry())
             .toLowerCase());
     HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
     stateCode = httpResponse.getStatusLine().getStatusCode();
     HttpEntity httpEntity = httpResponse.getEntity();
     if (httpEntity != null && stateCode == 200) {
       if (httpResponse.getEntity().getContentEncoding() == null
           || httpResponse
                   .getEntity()
                   .getContentEncoding()
                   .getValue()
                   .toLowerCase()
                   .indexOf("gzip")
               < 0) {
         InputStream is = httpEntity.getContent();
         byte[] byt = readInStream(is);
         return byt;
       } else {
         InputStream is =
             new GZIPInputStream(new ByteArrayInputStream(EntityUtils.toByteArray(httpEntity)));
         byte[] byt = readInStream(is);
         return byt;
       }
     }
   } catch (IOException e) {
   } catch (NullPointerException ex) {
   }
   return null;
 }
Пример #28
0
    @Override
    protected String doInBackground(String... url) {

      if (allPhoneContacts != null) {
        allPhoneContacts.clear();
      }

      if (syncedContacts != null) {
        syncedContacts.clear();
      }

      String resp = "";
      Header[] responseHeaders = null;
      HttpParams httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLSEC);
      HttpGet request = new HttpGet(url[0]);
      MyHttpClient Client = LogonClass.Client;
      Client.putContext(context);
      try {
        request.setHeader("syncstatus", "True");
        HttpResponse response = Client.execute(request);
        resp = EntityUtils.toString(response.getEntity());
        responseHeaders = response.getAllHeaders();
      } catch (Exception e) {

        resp = "none is righteous";
      }

      Log.v(TAG, "response is " + resp);
      return resp;
    }
Пример #29
0
    @Override
    protected Drawable doInBackground(String... param) {
      Drawable thumbnail = null;

      try {

        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet();
        httpGet.setURI(new URI(param[0]));
        httpGet.setHeader("Accept", "image/jpeg");

        HttpResponse response = httpClient.execute(httpGet);
        InputStream inputStream = response.getEntity().getContent();

        thumbnail = Drawable.createFromStream(inputStream, "src name");

      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      return thumbnail;
    }
Пример #30
0
  private void addCompanyInfo(String id) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpEntity httpEntity = null;
    HttpResponse httpResponse;
    HttpGet httpGet = new HttpGet(URLs.baseURL + id + ".json");

    httpGet.setHeader("Authorization", Token.CURRENT);

    String jsonStr = null;

    try {
      httpResponse = httpClient.execute(httpGet);
      if (httpResponse != null) {
        httpEntity = httpResponse.getEntity();
      }

      jsonStr = EntityUtils.toString(httpEntity);
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }

    if (jsonStr != null) {
      try {
        JSONObject company = new JSONObject(jsonStr);

        String name = company.getString("name");
        String image = company.getString("logo");
        companiesList.add(new Company(id, name, image));

      } catch (JSONException ex) {
        System.out.println(ex.getMessage());
      }
    }
  }