protected RetsHttpResponse execute(final HttpRequestBase method, Map<String, String> headers)
     throws RetsException {
   try {
     // add the default headers
     if (this.defaultHeaders != null) {
       for (Map.Entry<String, String> entry : this.defaultHeaders.entrySet()) {
         method.setHeader(entry.getKey(), entry.getValue());
       }
     }
     // add our request headers from rets
     if (headers != null) {
       for (Map.Entry<String, String> entry : headers.entrySet()) {
         method.setHeader(entry.getKey(), entry.getValue());
       }
     }
     // optional ua-auth stuff here
     if (this.userAgentPassword != null) {
       method.setHeader(RETS_UA_AUTH_HEADER, calculateUaAuthHeader(method, getCookies()));
     }
     // try to execute the request
     HttpResponse response = this.httpClient.execute(method);
     StatusLine status = response.getStatusLine();
     if (status.getStatusCode() != HttpStatus.SC_OK) {
       throw new InvalidHttpStatusException(status);
     }
     return new CommonsHttpClientResponse(response, getCookies());
   } catch (Exception e) {
     throw new RetsException(e);
   }
 }
 @Override
 protected void authenticate(IOperationMonitor monitor) throws IOException {
   UserCredentials credentials =
       getClient().getLocation().getCredentials(AuthenticationType.REPOSITORY);
   if (credentials == null) {
     throw new IllegalStateException("Authentication requested without valid credentials");
   }
   HttpRequestBase request =
       new HttpGet(
           baseUrl()
               + MessageFormat.format(
                   "/login?login={0}&password={1}",
                   new Object[] {credentials.getUserName(), credentials.getPassword()}));
   request.setHeader(CONTENT_TYPE, TEXT_XML_CHARSET_UTF_8);
   request.setHeader(ACCEPT, APPLICATION_JSON);
   HttpResponse response = getClient().execute(request, monitor);
   try {
     if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
       getClient().setAuthenticated(false);
       throw new AuthenticationException(
           "Authentication failed",
           new AuthenticationRequest<AuthenticationType<UserCredentials>>(
               getClient().getLocation(), AuthenticationType.REPOSITORY));
     } else {
       TypeToken<LoginToken> type = new TypeToken<LoginToken>() {};
       InputStream is = response.getEntity().getContent();
       InputStreamReader in = new InputStreamReader(is);
       LoginToken loginToken = new Gson().fromJson(in, type.getType());
       ((BugzillaRestHttpClient) getClient()).setLoginToken(loginToken);
       getClient().setAuthenticated(true);
     }
   } finally {
     HttpUtil.release(request, response, monitor);
   }
 }
 private HttpRequestBase getDefaultMethod(String paramString1, ArrayList<BasicNameValuePair> paramArrayList, String paramString2)
   throws FabException
 {
   Object localObject;
   try
   {
     StringBuilder localStringBuilder;
     String[] arrayOfString;
     int i;
     int j;
     if (paramString2.equalsIgnoreCase("POST"))
     {
       localObject = new HttpPost(new URI(paramString1));
       ((HttpRequestBase)localObject).setHeader("Content-type", "application/x-www-form-urlencoded");
       ((HttpRequestBase)localObject).setHeader("User-Agent", "Android");
       if (!TextUtils.isEmpty(FabSharedPrefs.getFabCookies()))
       {
         localStringBuilder = new StringBuilder();
         arrayOfString = FabSharedPrefs.getFabCookies().split("<==>");
         i = 0;
         j = arrayOfString.length;
       }
     }
     while (true)
     {
       if (i >= j)
       {
         ((HttpRequestBase)localObject).setHeader("Cookie", localStringBuilder.toString());
         if ((!TextUtils.isEmpty(FabEnvironment.reqAuth())) && (paramString1.contains(FabEnvironment.baseDomain())))
           ((HttpRequestBase)localObject).setHeader("Authorization", FabEnvironment.reqAuth());
         if ((paramArrayList == null) || (paramArrayList.isEmpty()))
           break label275;
         ((HttpPost)localObject).setEntity(new UrlEncodedFormEntity(paramArrayList, "UTF-8"));
         break label275;
         if (paramString2.equalsIgnoreCase("GET"))
         {
           localObject = new HttpGet(new URI(paramString1));
           break;
         }
         localObject = new HttpGet(new URI(paramString1));
         break;
       }
       localStringBuilder.append(arrayOfString[i].split("<@@>")[0] + "; ");
       i++;
     }
   }
   catch (URISyntaxException localURISyntaxException)
   {
     throw new FabException(localURISyntaxException);
   }
   catch (Exception localException)
   {
     throw new FabException(localException);
   }
   label275: return localObject;
 }
Example #4
0
  @Override
  protected String doInBackground(String... params) {

    HttpClient httpClient = new DefaultHttpClient();
    HttpRequestBase httpRequest = null;

    if (METHOD_NAME[0].equals(params[0])) {

      httpRequest = new HttpGet(URL.concat(METHOD_NAME[0]).concat("/51250652006"));
      httpRequest.setHeader("Content-type", "application/json");

    } else if (METHOD_NAME[1].equals(params[0])) {

      httpRequest = new HttpPost(URL.concat(METHOD_NAME[1]));
      httpRequest.setHeader("Content-type", "application/json");

      try {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cpf", "51250652006");
        jsonObject.put("nome", "Uguinho");
        jsonObject.put("dataNascimento", "1986-05-14"); // PESQUISAR
        // DATEFORMATE
        // JERSEY

        ((HttpPost) httpRequest)
            .setEntity(new ByteArrayEntity(jsonObject.toString().getBytes("UTF8")));

      } catch (JSONException e) {
        e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }

    } else if (METHOD_NAME[2].equals(params[0])) {

      httpRequest = new HttpGet(URL.concat(METHOD_NAME[2]));
      httpRequest.setHeader("Content-type", "application/json");
    }

    try {

      HttpResponse response = httpClient.execute(httpRequest);

      Log.i("ConsumeRESTAsyncTask", StreamToString.doIt(response.getEntity().getContent()));
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
  private static String apiCall(HttpRequestBase method) throws NetworkErrorException {

    Log.d("apiCall()", method.getURI().toString());
    String response = null;
    method.setHeader("User-Agent", "ANDROID DEBUG DEVICE");
    try {

      try {
        try {
          response = httpClient.execute(method, new BasicResponseHandler());
        } catch (IllegalStateException e) {
          throw new NetworkErrorException("404");
        }
        Log.d(TAG, response);
      } catch (HttpResponseException e) {
        Log.d(TAG, Integer.toString(e.getStatusCode()));
        throw new NetworkErrorException(Integer.toString(e.getStatusCode()));
      }

    } catch (IOException e) {
      Log.d(TAG, "IO");
      throw new NetworkErrorException("404");
    }
    Log.d("odpowiedz: ", response);
    return response;
  }
 public static HttpRequestBase buildHeaders(
     HttpRequestBase httpRequestBase, Map<String, String> headers) {
   for (Entry<String, String> header : headers.entrySet()) {
     httpRequestBase.setHeader(header.getKey(), header.getValue());
   }
   return httpRequestBase;
 }
 private UmssoCLInput initializeInput(HttpRequestBase request) {
   request.setHeader("Accept-Encoding", "gzip,deflate,sdch");
   return new UmssoCLInput(
       request,
       new UmSsoUserCredentialsCallback(
           getUmSsoHttpConnectionSettings().getUmssoUsername(),
           getUmSsoHttpConnectionSettings().getUmssoPassword()));
 }
 public static HttpRequestBase buildHeaders(
     HttpRequestBase httpRequestBase, Map<String, String> headers, HTTP_METHODS httpMethod) {
   Iterator<Entry<String, String>> iterator = headers.entrySet().iterator();
   while (iterator.hasNext()) {
     Entry<String, String> header = iterator.next();
     httpRequestBase.setHeader(header.getKey(), header.getValue());
   }
   return httpRequestBase;
 }
  private HttpResponse execute(
      HttpMethodEnum method, String path, HashMap<String, String> headers) {
    try {
      URI uri = URI.create(server.getEndpoint() + path);
      HttpResponse response;
      HttpRequestBase hrb;
      switch (method) {
        case GET:
          hrb = new HttpGet(uri);
          break;
        case PUT:
          hrb = new HttpPut(uri);
          break;
        case POST:
          hrb = new HttpPost(uri);
          break;
        case PATCH:
          hrb = new HttpPatch(uri);
          break;
          //      case Merge:
          //        hrb = new HttpMerge(uri);
          //        break;
        case DELETE:
          hrb = new HttpDelete(uri);
          break;
        default:
          throw new RuntimeException("Method unsupported: " + method);
      }

      if (null != headers) {
        for (String header : headers.keySet()) hrb.setHeader(header, headers.get(header));
      }

      response = client.execute(hrb);
      hrb.reset();
      return response;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Example #10
0
  @SuppressWarnings("deprecation")
  @Override
  public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) {
    HttpRequestBase httpMethod =
        (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String path = PropertyExpander.expandProperties(context, request.getPath());
    StringBuffer query = new StringBuffer();
    String encoding =
        System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding()));

    StringToStringMap responseProperties =
        (StringToStringMap) context.getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

    MimeMultipart formMp =
        "multipart/form-data".equals(request.getMediaType())
                && httpMethod instanceof HttpEntityEnclosingRequestBase
            ? new MimeMultipart()
            : null;

    RestParamsPropertyHolder params = request.getParams();

    for (int c = 0; c < params.getPropertyCount(); c++) {
      RestParamProperty param = params.getPropertyAt(c);

      String value = PropertyExpander.expandProperties(context, param.getValue());
      responseProperties.put(param.getName(), value);

      List<String> valueParts =
          sendEmptyParameters(request) || (!StringUtils.hasContent(value) && param.getRequired())
              ? RestUtils.splitMultipleParametersEmptyIncluded(
                  value, request.getMultiValueDelimiter())
              : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter());

      // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
      // the URI handling further down)
      if (value != null
          && param.getStyle() != ParameterStyle.HEADER
          && param.getStyle() != ParameterStyle.TEMPLATE
          && !param.isDisableUrlEncoding()) {
        try {
          if (StringUtils.hasContent(encoding)) {
            value = URLEncoder.encode(value, encoding);
            for (int i = 0; i < valueParts.size(); i++)
              valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding));
          } else {
            value = URLEncoder.encode(value);
            for (int i = 0; i < valueParts.size(); i++)
              valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
          }
        } catch (UnsupportedEncodingException e1) {
          SoapUI.logError(e1);
          value = URLEncoder.encode(value);
          for (int i = 0; i < valueParts.size(); i++)
            valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
        }
        // URLEncoder replaces space with "+", but we want "%20".
        value = value.replaceAll("\\+", "%20");
        for (int i = 0; i < valueParts.size(); i++)
          valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20"));
      }

      if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) {
        if (!StringUtils.hasContent(value) && !param.getRequired()) continue;
      }

      switch (param.getStyle()) {
        case HEADER:
          for (String valuePart : valueParts) httpMethod.addHeader(param.getName(), valuePart);
          break;
        case QUERY:
          if (formMp == null || !request.isPostQueryString()) {
            for (String valuePart : valueParts) {
              if (query.length() > 0) query.append('&');

              query.append(URLEncoder.encode(param.getName()));
              query.append('=');
              if (StringUtils.hasContent(valuePart)) query.append(valuePart);
            }
          } else {
            try {
              addFormMultipart(
                  request, formMp, param.getName(), responseProperties.get(param.getName()));
            } catch (MessagingException e) {
              SoapUI.logError(e);
            }
          }

          break;
        case TEMPLATE:
          try {
            value =
                getEncodedValue(
                    value,
                    encoding,
                    param.isDisableUrlEncoding(),
                    request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value);
          } catch (UnsupportedEncodingException e) {
            SoapUI.logError(e);
          }
          break;
        case MATRIX:
          try {
            value =
                getEncodedValue(
                    value,
                    encoding,
                    param.isDisableUrlEncoding(),
                    request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
          } catch (UnsupportedEncodingException e) {
            SoapUI.logError(e);
          }

          if (param.getType().equals(XmlBoolean.type.getName())) {
            if (value.toUpperCase().equals("TRUE") || value.equals("1")) {
              path += ";" + param.getName();
            }
          } else {
            path += ";" + param.getName();
            if (StringUtils.hasContent(value)) {
              path += "=" + value;
            }
          }
          break;
        case PLAIN:
          break;
      }
    }

    if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES))
      path = PathUtils.fixForwardSlashesInPath(path);

    if (PathUtils.isHttpPath(path)) {
      try {
        // URI(String) automatically URLencodes the input, so we need to
        // decode it first...
        URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
        context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
        java.net.URI oldUri = httpMethod.getURI();
        httpMethod.setURI(
            HttpUtils.createUri(
                oldUri.getScheme(),
                oldUri.getRawUserInfo(),
                oldUri.getHost(),
                oldUri.getPort(),
                oldUri.getRawPath(),
                uri.getEscapedQuery(),
                oldUri.getRawFragment()));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    } else if (StringUtils.hasContent(path)) {
      try {
        java.net.URI oldUri = httpMethod.getURI();
        String pathToSet =
            StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath())
                ? oldUri.getRawPath() + path
                : path;
        java.net.URI newUri =
            URIUtils.createURI(
                oldUri.getScheme(),
                oldUri.getHost(),
                oldUri.getPort(),
                pathToSet,
                oldUri.getQuery(),
                oldUri.getFragment());
        httpMethod.setURI(newUri);
        context.setProperty(
            BaseHttpRequestTransport.REQUEST_URI,
            new URI(
                newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    }

    if (query.length() > 0 && !request.isPostQueryString()) {
      try {
        java.net.URI oldUri = httpMethod.getURI();
        httpMethod.setURI(
            URIUtils.createURI(
                oldUri.getScheme(),
                oldUri.getHost(),
                oldUri.getPort(),
                oldUri.getRawPath(),
                query.toString(),
                oldUri.getFragment()));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    }

    if (request instanceof RestRequest) {
      String acceptEncoding = ((RestRequest) request).getAccept();
      if (StringUtils.hasContent(acceptEncoding)) {
        httpMethod.setHeader("Accept", acceptEncoding);
      }
    }

    if (formMp != null) {
      // create request message
      try {
        if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
          String requestContent =
              PropertyExpander.expandProperties(
                  context, request.getRequestContent(), request.isEntitizeProperties());
          if (StringUtils.hasContent(requestContent)) {
            initRootPart(request, requestContent, formMp);
          }
        }

        for (Attachment attachment : request.getAttachments()) {
          MimeBodyPart part = new PreencodedMimeBodyPart("binary");

          if (attachment instanceof FileAttachment<?>) {
            String name = attachment.getName();
            if (StringUtils.hasContent(attachment.getContentID())
                && !name.equals(attachment.getContentID())) name = attachment.getContentID();

            part.setDisposition(
                "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"");
          } else part.setDisposition("form-data; name=\"" + attachment.getName() + "\"");

          part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));

          formMp.addBodyPart(part);
        }

        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
        message.setContent(formMp);
        message.saveChanges();
        RestRequestMimeMessageRequestEntity mimeMessageRequestEntity =
            new RestRequestMimeMessageRequestEntity(message, request);
        ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
        httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
        httpMethod.setHeader("MIME-Version", "1.0");
      } catch (Throwable e) {
        SoapUI.logError(e);
      }
    } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
      if (StringUtils.hasContent(request.getMediaType()))
        httpMethod.setHeader(
            "Content-Type", getContentTypeHeader(request.getMediaType(), encoding));

      if (request.isPostQueryString()) {
        try {
          ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString()));
        } catch (UnsupportedEncodingException e) {
          SoapUI.logError(e);
        }
      } else {
        String requestContent =
            PropertyExpander.expandProperties(
                context, request.getRequestContent(), request.isEntitizeProperties());
        List<Attachment> attachments = new ArrayList<Attachment>();

        for (Attachment attachment : request.getAttachments()) {
          if (attachment.getContentType().equals(request.getMediaType())) {
            attachments.add(attachment);
          }
        }

        if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) {
          try {
            byte[] content =
                encoding == null ? requestContent.getBytes() : requestContent.getBytes(encoding);
            ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content));
          } catch (UnsupportedEncodingException e) {
            ((HttpEntityEnclosingRequest) httpMethod)
                .setEntity(new ByteArrayEntity(requestContent.getBytes()));
          }
        } else if (attachments.size() > 0) {
          try {
            MimeMultipart mp = null;

            if (StringUtils.hasContent(requestContent)) {
              mp = new MimeMultipart();
              initRootPart(request, requestContent, mp);
            } else if (attachments.size() == 1) {
              ((HttpEntityEnclosingRequest) httpMethod)
                  .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1));

              httpMethod.setHeader(
                  "Content-Type", getContentTypeHeader(request.getMediaType(), encoding));
            }

            if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) {
              if (mp == null) mp = new MimeMultipart();

              // init mimeparts
              AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap());

              // create request message
              MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
              message.setContent(mp);
              message.saveChanges();
              RestRequestMimeMessageRequestEntity mimeMessageRequestEntity =
                  new RestRequestMimeMessageRequestEntity(message, request);
              ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
              httpMethod.setHeader(
                  "Content-Type",
                  getContentTypeHeader(
                      mimeMessageRequestEntity.getContentType().getValue(), encoding));
              httpMethod.setHeader("MIME-Version", "1.0");
            }
          } catch (Exception e) {
            SoapUI.logError(e);
          }
        }
      }
    }
  }
 public static void signRequest(HttpRequestBase request, AuthenticationContext context) {
   request.setHeader("Authorization", "Bearer " + context.getAccessToken());
 }