Ejemplo n.º 1
1
 protected Object execute(Request request, HttpUriRequest httpReq) throws Exception {
   for (Map.Entry<String, String> entry : request.entrySet()) {
     httpReq.setHeader(entry.getKey(), entry.getValue());
   }
   HttpResponse resp = executeRequestWithTimeout(httpReq);
   HttpEntity entity = resp.getEntity();
   int status = resp.getStatusLine().getStatusCode();
   if (entity == null) {
     if (status < 400) {
       return null;
     }
     throw new RemoteException(status, "ServerError", "Server Error", (Throwable) null);
   }
   Header ctypeHeader = entity.getContentType();
   if (ctypeHeader == null) { // handle broken responses with no ctype
     if (status != 200) {
       // this may happen when login failed
       throw new RemoteException(status, "ServerError", "Server Error", (Throwable) null);
     }
     return null; // cannot handle responses with no ctype
   }
   String ctype = ctypeHeader.getValue();
   String disp = null;
   Header[] hdisp = resp.getHeaders("Content-Disposition");
   if (hdisp != null && hdisp.length > 0) {
     disp = hdisp[0].getValue();
   }
   return request.handleResult(status, ctype, disp, entity.getContent());
 }
Ejemplo n.º 2
0
  byte[] readBody(HttpResponse httpResponse) throws Exception {
    if (httpResponse == null) return null;
    httpEntity = httpResponse.getEntity();
    if (httpEntity == null) return null;

    Header zipHeader = httpResponse.getFirstHeader("zip");
    boolean zip = zipHeader != null && "true".equals(zipHeader.getValue());

    TimerMonitor timerMonitor = new TimerMonitor(this);
    timerMonitor.startSession();

    contentLengthHeader = httpResponse.getFirstHeader(CONTENT_LENGTH);

    try {
      byte[] bytes = readBody(contentLengthHeader);
      if (zip) bytes = new GZipIO().unzip(bytes);
      if (bytes == null || bytes.length < 1) return bytes;
      readData = bytes.length;
      return decodeResponse(bytes, httpEntity.getContentEncoding());
    } finally {
      if (httpEntity instanceof BasicManagedEntity) {
        BasicManagedEntity entity = (BasicManagedEntity) httpEntity;
        //        System.out.println(" hihi  da thay roi 2 " + entity);
        entity.releaseConnection();
      } else {
        if (httpEntity.getContent() != null) httpEntity.getContent().close();
      }
    }
  }
Ejemplo n.º 3
0
  // function get json from url
  // by making HTTP POST or GET mehtod
  public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {

    // Making HTTP request
    try {

      // check for request method
      if (method == "POST") {
        // request method is POST
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

      } else if (method == "GET") {
        // request method is GET
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String paramString = URLEncodedUtils.format(params, "utf-8");
        url += "?" + paramString;
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
      }

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
      is.close();
      json = sb.toString();
    } catch (Exception e) {
      Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
      jObj = new JSONObject(json);
    } catch (JSONException e) {
      Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;
  }
Ejemplo n.º 4
0
 /*
  * Assert.asserts that two request or response bodies are byte-equivalent.
  */
 public static boolean equivalent(HttpEntity e1, HttpEntity e2) throws Exception {
   InputStream i1 = e1.getContent();
   InputStream i2 = e2.getContent();
   if (i1 == null && i2 == null) return true;
   if (i1 == null || i2 == null) return false; // avoid possible NPEs below
   int b1 = -1;
   while ((b1 = i1.read()) != -1) {
     if (b1 != i2.read()) return false;
   }
   return (-1 == i2.read());
 }
Ejemplo n.º 5
0
  public InputStream doPostInputStream(String url, List<NameValuePair> params)
      throws IOException, ReaderException {
    //		Log.d(TAG, "[DEBUG] POST: " + url);
    //		Log.d(TAG, "[DEBUG] PARAMS: " + params);
    //		Log.d(TAG, "[DEBUG] Authorization: " + "GoogleLogin auth=" + this.auth);
    HttpPost post = new HttpPost(url);
    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

    if (this.auth != null) post.setHeader("Authorization", "GoogleLogin auth=" + this.auth);

    // gzip
    post.setHeader("User-agent", "gzip");
    post.setHeader("Accept-Encoding", "gzip");

    HttpResponse res = getClient().execute(post);
    int resStatus = res.getStatusLine().getStatusCode();

    if (resStatus == HttpStatus.SC_FORBIDDEN) throw new ReaderLoginException("Login failure");
    else if (resStatus == HttpStatus.SC_UNAUTHORIZED)
      throw new ReaderLoginException("Authentication fails (" + resStatus + "): " + url);
    else if (resStatus != HttpStatus.SC_OK) {
      throw new ReaderException("Invalid http status " + resStatus + ": " + url);
    }

    final HttpEntity entity = res.getEntity();
    if (entity == null) {
      throw new ReaderException("null response entity");
    }

    InputStream is = null;

    // create the appropriate stream wrapper based on the encoding type
    String encoding = Utils.getHeaderValue(entity.getContentEncoding());
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
      is = new GZIPInputStream(entity.getContent());
    } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
      is = new InflaterInputStream(entity.getContent(), new Inflater(true));
    } else {
      is = entity.getContent();
    }

    return new FilterInputStream(is) {
      @Override
      public void close() throws IOException {
        super.close();
        entity.consumeContent();
      }
    };
  }
  public boolean deleteRequest(String path) {
    log.info("deleteRequest(" + path + ")");
    // http://msdn.microsoft.com/en-us/library/windowsazure/dn151676.aspx
    HttpDelete httpDelete = new HttpDelete(getAPIEndPoint(path));
    httpDelete.addHeader("Authorization", this.getToken());
    httpDelete.addHeader("Content-Type", "application/json");
    httpDelete.addHeader("DataServiceVersion", "3.0;NetFx");
    httpDelete.addHeader("MaxDataServiceVersion", "3.0;NetFx");

    HttpClient httpClient = HttpClientBuilder.create().build();

    try {
      HttpResponse response = httpClient.execute(httpDelete);
      HttpEntity entity = response.getEntity();

      if (response.getStatusLine().getStatusCode() != 204) {
        log.error("An error occured when deleting an object in Office 365");
        this.invalidateToken();
        StringBuffer sb = new StringBuffer();
        if (entity != null && entity.getContent() != null) {
          BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
          String s = null;

          log.info("Response :{0}", response.getStatusLine().toString());

          while ((s = in.readLine()) != null) {
            sb.append(s);
            log.info(s);
          }
        }
        throw new ConnectorException(
            "Delete Object failed to "
                + path
                + ". Error code was "
                + response.getStatusLine().getStatusCode()
                + ". Received the following response "
                + sb.toString());
      } else {
        return true;
      }
    } catch (ClientProtocolException cpe) {
      log.error(cpe, "Error doing deleteRequest to path {0}", path);
      throw new ConnectorException("Exception whilst doing DELETE to " + path);
    } catch (IOException ioe) {
      log.error(ioe, "IOE Error doing deleteRequest to path {0}", path);
      throw new ConnectorException("Exception whilst doing DELETE to " + path);
    }
  }
  private Map<String, String> loadAllToks(final String code, int port, final HttpClient httpClient)
      throws IOException {
    final HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
    try {
      final List<? extends NameValuePair> nvps =
          Arrays.asList(
              new BasicNameValuePair("code", code),
              new BasicNameValuePair("client_id", model.getSettings().getClientID()),
              new BasicNameValuePair("client_secret", model.getSettings().getClientSecret()),
              new BasicNameValuePair("redirect_uri", OauthUtils.getRedirectUrl(port)),
              new BasicNameValuePair("grant_type", "authorization_code"));
      final HttpEntity entity = new UrlEncodedFormEntity(nvps, LanternConstants.UTF8);
      post.setEntity(entity);

      log.debug("About to execute post!");
      final HttpResponse response = httpClient.execute(post);

      log.debug("Got response status: {}", response.getStatusLine());
      final HttpEntity responseEntity = response.getEntity();
      final String body = IOUtils.toString(responseEntity.getContent());
      EntityUtils.consume(responseEntity);

      final Map<String, String> oauthToks = JsonUtils.OBJECT_MAPPER.readValue(body, Map.class);
      log.debug("Got oath data: {}", oauthToks);
      return oauthToks;
    } finally {
      post.reset();
    }
  }
Ejemplo n.º 8
0
  @Test
  public void testMultipart() throws IOException, JSONException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:" + PORT + "/");

    File image = new File("resources/test/base.png");
    FileBody imagePart = new FileBody(image);
    StringBody messagePart = new StringBody("some message");

    MultipartEntity req = new MultipartEntity();
    req.addPart("image", imagePart);
    req.addPart("message", messagePart);
    httppost.setEntity(req);

    ImageEchoServer server = new ImageEchoServer(PORT);
    HttpResponse response = httpclient.execute(httppost);
    server.stop();

    HttpEntity resp = response.getEntity();
    assertThat(resp.getContentType().getValue(), is("application/json"));

    // sweet one-liner to convert an inputstream to a string from stackoverflow:
    // http://stackoverflow.com/questions/309424/in-java-how-do-i-read-convert-an-inputstream-to-a-string
    String out = new Scanner(resp.getContent()).useDelimiter("\\A").next();

    JSONObject json = new JSONObject(out);

    String base64 = Base64.encodeFromFile("resources/test/base.png");

    assertThat(json.getString("screenshot"), is(base64));
    assertThat(json.getBoolean("imageEcho"), is(true));
  }
Ejemplo n.º 9
0
  @Override
  protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    try {
      StringEntity se;
      // Log.e("http string",URL+"//"+send.toString());
      HttpParams httpParameters = new BasicHttpParams(); // set connection parameters
      HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);
      HttpConnectionParams.setSoTimeout(httpParameters, 60000);
      HttpClient httpclient = new DefaultHttpClient(httpParameters);
      HttpResponse response = null;
      HttpPost httppost = new HttpPost(params[0]);
      httppost.setHeader("Content-type", "application/json");
      se = new StringEntity(params[1]);
      se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
      httppost.setEntity(se);
      response = httpclient.execute(httppost);
      HttpEntity entity = response.getEntity();
      InputStream is = entity.getContent();
      streamtostring(is);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
Ejemplo n.º 10
0
  public static StringBuilder getResponseString(HttpResponse result) {
    if (result == null) {
      return null;
    }
    StringBuilder builder = new StringBuilder("");

    HttpEntity res = result.getEntity();
    InputStream is = null;
    try {
      is = res.getContent();
    } catch (IllegalStateException e) {
      Log.d("ResponseString", "Response invalid (IllegalStateException) " + e.getMessage());
      return builder;
    } catch (IOException e) {
      Log.d("ResponseString", "Response invalid (IoException)  " + e.getMessage());
      return builder;
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    String line = null;
    try {
      while ((line = br.readLine()) != null) {
        builder.append(line);
      }
    } catch (IOException e) {
      Log.d("ResponseString", "IOException " + e.getMessage());
      return builder;
    }
    return builder;
  }
Ejemplo n.º 11
0
  public void propfind(HttpPropfind.Mode mode)
      throws URISyntaxException, IOException, DavException, HttpException {
    @Cleanup CloseableHttpResponse response = null;

    // processMultiStatus() requires knowledge of the actual content location,
    // so we have to handle redirections manually and create a new request for the new location
    for (int i = context.getRequestConfig().getMaxRedirects(); i > 0; i--) {
      HttpPropfind propfind = new HttpPropfind(location, mode);
      response = httpClient.execute(propfind, context);

      if (response.getStatusLine().getStatusCode() / 100 == 3) {
        location = DavRedirectStrategy.getLocation(propfind, response, context);
        Log.i(TAG, "Redirection on PROPFIND; trying again at new content URL: " + location);
        // don't forget to throw away the unneeded response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
          @Cleanup InputStream content = entity.getContent();
        }
      } else break; // answer was NOT a redirection, continue
    }
    if (response == null) throw new DavNoContentException();

    checkResponse(response); // will also handle Content-Location
    processMultiStatus(response);
  }
  private static Bitmap getCaptchaImage(HttpClient client, String captchaId)
      throws ClientProtocolException, IOException {
    final HttpGet request = new HttpGet(String.format(CAPTCHA_IMAGE, captchaId));
    request.addHeader("User-Agent", USER_AGENT);
    request.addHeader("Referer", REFERER);
    request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

    final HttpResponse response = client.execute(request);

    final HttpEntity entity = response.getEntity();
    final InputStream in = entity.getContent();

    int next;
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while ((next = in.read()) != -1) {
      bos.write(next);
    }
    bos.flush();
    byte[] result = bos.toByteArray();

    bos.close();

    entity.consumeContent();
    return BitmapFactory.decodeByteArray(result, 0, result.length);
  }
Ejemplo n.º 13
0
  public static String sendSSLPost(String url) throws ClientProtocolException, IOException {
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    CloseableHttpClient httpClient = HttpClientUtil.createSSLClientDefault();
    HttpGet getdd = new HttpGet();
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");

    // httpPost.setEntity(new StringEntity(JSON.toJSONString(param), "UTF-8"));

    HttpResponse response = httpClient.execute(httpPost);
    if (response.getStatusLine().getStatusCode() == 200) {

      org.apache.http.HttpEntity httpEntity = response.getEntity();

      if (httpEntity != null) {
        try {
          BufferedReader bufferedReader =
              new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8 * 1024);
          while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
          }

        } catch (Exception e) {

        }
      }
    }
    return stringBuilder.toString();
  }
Ejemplo n.º 14
0
  /**
   * HttpClient方式实现,支持验证指定证书
   *
   * @throws ClientProtocolException
   * @throws IOException
   */
  public void initSSLCertainWithHttpClient() throws ClientProtocolException, IOException {
    int timeOut = 30 * 1000;
    HttpParams param = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(param, timeOut);
    HttpConnectionParams.setSoTimeout(param, timeOut);
    HttpConnectionParams.setTcpNoDelay(param, true);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", TrustCertainHostNameFactory.getDefault(this), 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(param, registry);
    DefaultHttpClient client = new DefaultHttpClient(manager, param);

    // HttpGet request = new
    // HttpGet("https://certs.cac.washington.edu/CAtest/");
    HttpGet request = new HttpGet("https://www.alipay.com/");
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
    StringBuilder result = new StringBuilder();
    String line = "";
    while ((line = reader.readLine()) != null) {
      result.append(line);
    }
    Log.e("HTTPS TEST", result.toString());
  }
Ejemplo n.º 15
0
  /**
   * Get a new modhash by scraping and return it
   *
   * @param client
   * @return
   */
  public static String doUpdateModhash(HttpClient client) {
    final Pattern MODHASH_PATTERN = Pattern.compile("modhash: '(.*?)'");
    String modhash;
    HttpEntity entity = null;
    // The pattern to find modhash from HTML javascript area
    try {
      HttpGet httpget = new HttpGet(Constants.MODHASH_URL);
      HttpResponse response = client.execute(httpget);

      // For modhash, we don't care about the status, since the 404 page has the info we want.
      //    		status = response.getStatusLine().toString();
      //        	if (!status.contains("OK"))
      //        		throw new HttpException(status);

      entity = response.getEntity();

      BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
      // modhash should appear within first 1200 chars
      char[] buffer = new char[1200];
      in.read(buffer, 0, 1200);
      in.close();
      String line = String.valueOf(buffer);
      entity.consumeContent();

      if (StringUtils.isEmpty(line)) {
        throw new HttpException(
            "No content returned from doUpdateModhash GET to " + Constants.MODHASH_URL);
      }
      if (line.contains("USER_REQUIRED")) {
        throw new Exception("User session error: USER_REQUIRED");
      }

      Matcher modhashMatcher = MODHASH_PATTERN.matcher(line);
      if (modhashMatcher.find()) {
        modhash = modhashMatcher.group(1);
        if (StringUtils.isEmpty(modhash)) {
          // Means user is not actually logged in.
          return null;
        }
      } else {
        throw new Exception("No modhash found at URL " + Constants.MODHASH_URL);
      }

      if (Constants.LOGGING) Common.logDLong(TAG, line);

      if (Constants.LOGGING) Log.d(TAG, "modhash: " + modhash);
      return modhash;

    } catch (Exception e) {
      if (entity != null) {
        try {
          entity.consumeContent();
        } catch (Exception e2) {
          if (Constants.LOGGING) Log.e(TAG, "entity.consumeContent()", e);
        }
      }
      if (Constants.LOGGING) Log.e(TAG, "doUpdateModhash()", e);
      return null;
    }
  }
Ejemplo n.º 16
0
  public static JSONObject doPost(String url, JSONObject obj) {
    JSONObject json = null;
    try {
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url);
      //	httpPost.setHeader("Accept", "application/json");
      httpPost.setHeader("Content-type", "application/json");

      StringEntity se = new StringEntity(obj.toString());
      httpPost.setEntity(se);

      HttpResponse response;
      response = httpclient.execute(httpPost);
      HttpEntity entity = response.getEntity();
      if (entity != null) {
        InputStream instream = entity.getContent();
        String result = convertStreamToString(instream);
        json = new JSONObject(result);
        instream.close();
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return json;
  }
Ejemplo n.º 17
0
  public JSONObject makeHttpRequest(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {

      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url);
      // Depends on your web service
      httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
      httpPost.setEntity(new UrlEncodedFormEntity(params));
      HttpResponse httpResponse = httpClient.execute(httpPost);
      HttpEntity httpEntity = httpResponse.getEntity();
      InputStreamReader isr = new InputStreamReader(httpEntity.getContent());
      BufferedReader reader = new BufferedReader(isr);
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
      json = sb.toString();
    } catch (Exception e) {
      Log.e("Buffer Error", "::::Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
      jObj = new JSONObject(json);
    } catch (JSONException e) {
      Log.e("JSON Parser", "::::Error parsing data " + e.toString());
    }
    return jObj;
  }
Ejemplo n.º 18
0
  /**
   * Converts a generic {@link HttpEntity} object into a {@link ServerResponse} object by reading
   * the content supplied in the raw server response, and creating a {@link JSONObject} that
   * contains the same data. This data is then attached as the post data of the {@link
   * ServerResponse} object returned.
   *
   * @param entity A generic {@link HttpEntity} returned as a result of a HTTP response.
   * @param statusCode An {@link Integer} value containing the HTTP response code.
   * @param tag A {@link String} value containing the tag value to be applied to the resultant
   *     {@link ServerResponse} object.
   * @param log A {@link Boolean} value indicating whether or not to log the raw content lines via
   *     the debug interface.
   * @param linkData A {@link BranchLinkData} object containing the data dictionary associated with
   *     the link subject of the original server request.
   * @return A {@link ServerResponse} object representing the {@link HttpEntity} response in Branch
   *     SDK terms.
   * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP/1.1: Status
   *     Codes</a>
   */
  private ServerResponse processEntityForJSON(
      HttpEntity entity, int statusCode, String tag, boolean log, BranchLinkData linkData) {
    ServerResponse result = new ServerResponse(tag, statusCode, linkData);
    try {
      if (entity != null) {
        InputStream instream = entity.getContent();
        BufferedReader rd = new BufferedReader(new InputStreamReader(instream));

        String line = rd.readLine();
        if (log) PrefHelper.Debug("BranchSDK", "returned " + line);

        if (line != null) {
          try {
            JSONObject jsonObj = new JSONObject(line);
            result.setPost(jsonObj);
          } catch (JSONException ex) {
            try {
              JSONArray jsonArray = new JSONArray(line);
              result.setPost(jsonArray);
            } catch (JSONException ex2) {
              if (log)
                PrefHelper.Debug(getClass().getSimpleName(), "JSON exception: " + ex2.getMessage());
            }
          }
        }
      }
    } catch (IOException ex) {
      if (log) PrefHelper.Debug(getClass().getSimpleName(), "IO exception: " + ex.getMessage());
    }
    return result;
  }
Ejemplo n.º 19
0
  public static InputStream post(Context context, String url, ArrayList<NameValuePair> params) {

    mLogger = Logger.getLogger();

    InputStream in = null;

    try {
      UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, CHARSET);

      HttpPost request = new HttpPost(url);

      request.setEntity(entity);

      HttpClient client = getInstance(context);
      HttpResponse response = client.execute(request);
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

        HttpEntity resEntity = response.getEntity();

        in = (resEntity == null) ? null : resEntity.getContent();
      }
    } catch (IOException e) {

      e.printStackTrace();
      mLogger.e("error:" + e.getMessage());
    } catch (Exception e) {

      e.printStackTrace();
      mLogger.e("error:" + e.getMessage());
    }

    return in;
  }
 private boolean doesResponseIndicatePortal(HttpEntity response) {
   try {
     return doesResponseContentIndicatePortal(response.getContent());
   } catch (IOException e) {
     throw new RuntimeException("Error reading response", e);
   }
 }
Ejemplo n.º 21
0
  public final String[] post(String url, String json) {
    String[] result = new String[2];
    try {

      HttpPost httpPost = new HttpPost(new URI(url));
      httpPost.setHeader("Content-type", "application/json");
      StringEntity sEntity = new StringEntity(json, "UTF-8");
      httpPost.setEntity(sEntity);

      HttpResponse response;
      response = HttpClientSingleton.getHttpClientInstace().execute(httpPost);
      HttpEntity entity = response.getEntity();

      if (entity != null) {
        result[0] = String.valueOf(response.getStatusLine().getStatusCode());
        InputStream instream = entity.getContent();
        result[1] = toString(instream);
        instream.close();
        Log.d("post", "Result from post JsonPost : " + result[0] + " : " + result[1]);
      }

    } catch (Exception e) {
      Log.e("NGVL", "Falha ao acessar Web service", e);
      result[0] = "0";
      result[1] = "Falha de rede!";
    }
    return result;
  }
Ejemplo n.º 22
0
  public String httpGetAPICall(String requestURL) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(requestURL);

    try {

      HttpResponse response = client.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        }
      } else {
        Log.e(MainActivity.class.toString(), "Failedet JSON object");
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return builder.toString();
  }
Ejemplo n.º 23
0
  private void executeRequest(HttpUriRequest request, String url) {
    HttpClient client = new DefaultHttpClient();

    HttpResponse httpResponse;

    try {
      httpResponse = client.execute(request);
      responseCode = httpResponse.getStatusLine().getStatusCode();
      message = httpResponse.getStatusLine().getReasonPhrase();

      HttpEntity entity = httpResponse.getEntity();

      if (entity != null) {

        InputStream instream = entity.getContent();
        Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
          instream = new GZIPInputStream(instream);
        }
        response = convertStreamToString(instream);

        // Closing the input stream will trigger connection release
        instream.close();
      }

    } catch (ClientProtocolException e) {
      client.getConnectionManager().shutdown();
      e.printStackTrace();
    } catch (IOException e) {
      client.getConnectionManager().shutdown();
    }
  }
 public static byte[] httpEntityToByteArray(final HttpEntity entity) throws IOException {
   if (entity == null) {
     throw new IllegalArgumentException("HTTP entity may not be null");
   }
   InputStream instream = entity.getContent();
   if (instream == null) {
     return new byte[] {};
   }
   if (entity.getContentLength() > Integer.MAX_VALUE) {
     throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
   }
   int i = (int) entity.getContentLength();
   if (i < 0) {
     i = 4096;
   }
   ByteArrayBuffer buffer = new ByteArrayBuffer(i);
   try {
     byte[] tmp = new byte[4096];
     int l;
     while ((l = instream.read(tmp)) != -1) {
       if (Thread.interrupted())
         throw new InterruptedIOException("File download process was canceled");
       buffer.append(tmp, 0, l);
     }
   } finally {
     instream.close();
   }
   return buffer.toByteArray();
 }
 @Override
 byte[] getResponseData(HttpEntity entity) throws IOException {
   if (entity != null) {
     InputStream instream = entity.getContent();
     long contentLength = entity.getContentLength();
     FileOutputStream buffer = new FileOutputStream(this.mFile);
     if (instream != null) {
       try {
         byte[] tmp = new byte[BUFFER_SIZE];
         int l, count = 0;
         // do not send messages if request has been cancelled
         while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
           count += l;
           buffer.write(tmp, 0, l);
           sendProgressMessage(count, (int) contentLength);
         }
       } finally {
         instream.close();
         buffer.flush();
         buffer.close();
       }
     }
   }
   return null;
 }
  @Test
  public void testCanParseBoxServerError()
      throws BoxRestException, IllegalStateException, IOException, BoxJSONException {
    BoxJSONParser jsonParser = new BoxJSONParser(new BoxResourceHub());
    EasyMock.reset(boxResponse, response, entity);
    inputStream =
        new ByteArrayInputStream(jsonParser.convertBoxObjectToJSONString(error).getBytes());
    EasyMock.expect(boxResponse.getHttpResponse()).andStubReturn(response);
    EasyMock.expect(response.getEntity()).andStubReturn(entity);
    EasyMock.expect(entity.getContent()).andStubReturn(inputStream);
    EasyMock.expect(entity.isStreaming()).andStubReturn(false);

    EasyMock.expect(boxResponse.getHttpResponse()).andStubReturn(response);
    EasyMock.expect(response.getStatusLine()).andStubReturn(statusLine);
    EasyMock.expect(statusLine.getStatusCode()).andStubReturn(statusCode);

    EasyMock.replay(boxResponse, response, entity, statusLine);
    ErrorResponseParser parser = new ErrorResponseParser(jsonParser);
    Object object = parser.parse(boxResponse);
    Assert.assertEquals(BoxServerError.class, object.getClass());

    Assert.assertEquals(
        jsonParser.convertBoxObjectToJSONString(error),
        jsonParser.convertBoxObjectToJSONString(object));
    EasyMock.verify(boxResponse, response, entity, statusLine);
  }
Ejemplo n.º 27
0
  public static List<RoleRepresentation> getRealmRoles(HttpServletRequest req) throws Failure {
    KeycloakSecurityContext session =
        (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());

    HttpClient client = new HttpClientBuilder().disableTrustManager().build();
    try {
      HttpGet get =
          new HttpGet(
              AdapterUtils.getOriginForRestCalls(req.getRequestURL().toString(), session)
                  + "/auth/admin/realms/demo/roles");
      get.addHeader("Authorization", "Bearer " + session.getTokenString());
      try {
        HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() != 200) {
          throw new Failure(response.getStatusLine().getStatusCode());
        }
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        try {
          return JsonSerialization.readValue(is, TypedList.class);
        } finally {
          is.close();
        }
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } finally {
      client.getConnectionManager().shutdown();
    }
  }
Ejemplo n.º 28
0
  /**
   * 将Entity的内容载入Page对象
   *
   * @date 2013-1-7 上午11:22:06
   * @param entity
   * @return
   * @throws Exception
   */
  private Page load(HttpEntity entity) throws Exception {
    Page page = new Page();

    // 设置返回内容的ContentType
    String contentType = null;
    Header type = entity.getContentType();
    if (type != null) contentType = type.getValue();
    page.setContentType(contentType);

    // 设置返回内容的字符编码
    String contentEncoding = null;
    Header encoding = entity.getContentEncoding();
    if (encoding != null) contentEncoding = encoding.getValue();
    page.setEncoding(contentEncoding);

    // 设置返回内容的字符集
    String contentCharset = EntityUtils.getContentCharSet(entity);
    page.setCharset(contentCharset);
    // 根据配置文件设置的字符集参数进行内容二进制话
    String charset = config.getCharset();
    String content = this.read(entity.getContent(), charset);
    page.setContent(content);
    //		if (charset == null || charset.trim().length() == 0)
    //			page.setContentData(content.getBytes());
    //		else
    //			page.setContentData(content.getBytes(charset));

    return page;
  }
  /**
   * 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;
  }
Ejemplo n.º 30
-1
  @Test
  public void testGetAndCheckKey() throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://*****:*****@gmail.com"));
    nvps.add(new BasicNameValuePair("password", "Purbrick7"));
    post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    HttpResponse response = httpClient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
    HttpEntity entity = response.getEntity();
    String responseContent = IOUtils.toString(entity.getContent());
    System.out.println(response.getFirstHeader("Content-Type"));
    System.out.println(responseContent);

    JSONObject jsonObj = (JSONObject) new JSONParser().parse(responseContent);

    HttpPost post2 = new HttpPost("http://*****:*****@gmail.com"));
    nvps2.add(new BasicNameValuePair("authKey", (String) jsonObj.get("authKey")));
    post2.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8));

    HttpResponse response2 = httpClient.execute(post2);
    assertEquals(200, response2.getStatusLine().getStatusCode());
  }