示例#1
0
  private void createHttpClient2() {
    AndroidHttpClient httpClient = AndroidHttpClient.newInstance("MMS 1.0");
    String url = "http://www.baidu.com";
    byte[] pdu;

    try {
      URI hostUrl = new URI(url);
      HttpHost target =
          new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
      HttpPost post = new HttpPost(url);
      HttpRequest req = null;

      pdu = new byte[2];
      pdu[0] = (byte) MESSAGE_TYPE;
      pdu[1] = (byte) MESSAGE_TYPE_SEND_REQ;

      ByteArrayEntity entity = new ByteArrayEntity(pdu);
      entity.setContentType("application/vnd.wap.mms-message");
      post.setEntity(entity);
      req = post;

      final HttpResponse execute = httpClient.execute(target, req);
    } catch (URISyntaxException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
示例#2
0
  public static void writeDataToRequest(
      HttpRequest newWebRequest, String postedData, boolean disableRequestCompression) {

    HttpEntityEnclosingRequestBase requestMethod = (HttpEntityEnclosingRequestBase) newWebRequest;

    try {
      if (disableRequestCompression) {
        StringEntity entity = new StringEntity(postedData, ContentType.APPLICATION_JSON);
        entity.setChunked(true);
        requestMethod.setEntity(entity);
      } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzipOS = new GZIPOutputStream(baos);
        IOUtils.write(postedData, gzipOS, Consts.UTF_8.name());
        IOUtils.closeQuietly(gzipOS);
        ByteArrayEntity entity =
            new ByteArrayEntity(baos.toByteArray(), ContentType.APPLICATION_JSON);
        entity.setChunked(true);
        requestMethod.setEntity(entity);
      }

    } catch (IOException e) {
      throw new RuntimeException("Unable to gzip data!", e);
    }
  }
  private void initQuery() throws IOException {
    Hashtable<String, String> map = new Hashtable<String, String>();
    map.put("uid", "TEMP_USER");
    map.put("pwd", "TEMP_PASSWORD");
    map.put(QUERY_PARAM, Base64.encodeToString(TEST_QUERY.getBytes(), 0));

    HttpParams params = new BasicHttpParams();

    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, ConnectionManager.DEFAULT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, ConnectionManager.DEFAULT_TIMEOUT);
    DefaultHttpClient httpClient = new DefaultHttpClient(params);

    // create post method
    HttpPost postMethod = new HttpPost(QUERY_URI);

    ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
    ObjectOutputStream objOS = new ObjectOutputStream(byteArrayOS);
    objOS.writeObject(map);
    ByteArrayEntity req_entity = new ByteArrayEntity(byteArrayOS.toByteArray());
    req_entity.setContentType(MIMETypeConstantsIF.BINARY_TYPE);

    // associating entity with method
    postMethod.setEntity(req_entity);

    // Executing post method
    executeHttpClient(httpClient, postMethod);
  }
示例#4
0
  public String put(String url, Map<String, String> headers, byte[] data)
      throws ClientProtocolException, IOException, AuthorizationDeniedException {
    // create request
    HttpPut request = new HttpPut(url);

    // add data to request if necessary
    if (data != null) {
      ByteArrayEntity entity = new ByteArrayEntity(data);
      entity.setChunked(true);
      entity.setContentType("text/xml");
      request.setEntity(entity);
    }

    if (logger.isDebugEnabled()) {
      logger.debug("getting url: " + url);
    }

    // add headers to request if necessary
    if (headers != null && headers.size() > 0) {
      for (String header : headers.keySet()) {
        String value = headers.get(header);
        request.addHeader(header, value);

        if (logger.isDebugEnabled()) {
          logger.debug("adding header: " + header + " = " + value);
        }
      }
    }

    return process(request);
  }
 public void post(String feedUrl, byte[] data, String contentType, Operation operation)
     throws IOException {
   ByteArrayEntity entity = getCompressedEntity(data);
   entity.setContentType(contentType);
   HttpPost post = new HttpPost(feedUrl);
   post.setEntity(entity);
   callMethod(post, operation);
 }
  /**
   * Set the given serialized remote invocation as request body.
   *
   * <p>The default implementation simply sets the serialized invocation as the HttpPost's request
   * body. This can be overridden, for example, to write a specific encoding and to potentially set
   * appropriate HTTP request headers.
   *
   * @param config the HTTP invoker configuration that specifies the target service
   * @param httpPost the HttpPost to set the request body on
   * @param baos the ByteArrayOutputStream that contains the serialized RemoteInvocation object
   * @throws java.io.IOException if thrown by I/O methods
   */
  protected void setRequestBody(
      HttpInvokerClientConfiguration config, HttpPost httpPost, ByteArrayOutputStream baos)
      throws IOException {

    ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
    entity.setContentType(getContentType());
    httpPost.setEntity(entity);
  }
 public static HttpEntity generateJSONEntity(JSONObject json) {
   ByteArrayEntity retval = null;
   try {
     retval = new ByteArrayEntity(json.toString().getBytes("UTF-8"));
   } catch (UnsupportedEncodingException e) {
     throw new RuntimeException(e);
   }
   retval.setContentType("application/json");
   return retval;
 }
示例#8
0
 public static byte[] decompress(String alg, byte[] content) throws Exception {
   // Use the excellent content encoding handling that exists in HTTP Client
   HttpResponse response =
       new BasicHttpResponse(new BasicStatusLine(new HttpVersion(1, 0), 0, null));
   ByteArrayEntity entity = new ByteArrayEntity(content);
   entity.setContentEncoding(alg);
   response.setEntity(entity);
   new ResponseContentEncoding().process(response, null);
   return IOUtils.toByteArray(response.getEntity().getContent());
 }
 /**
  * Handles the given exception and generates an HTTP response to be sent back to the client to
  * inform about the exceptional condition encountered in the course of the request processing.
  *
  * @param ex the exception.
  * @param response the HTTP response.
  */
 protected void handleException(final HttpException ex, final HttpResponse response) {
   if (ex instanceof MethodNotSupportedException) {
     response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
   } else if (ex instanceof UnsupportedHttpVersionException) {
     response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED);
   } else if (ex instanceof ProtocolException) {
     response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
   } else {
     response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
   }
   byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage());
   ByteArrayEntity entity = new ByteArrayEntity(msg);
   entity.setContentType("text/plain; charset=US-ASCII");
   response.setEntity(entity);
 }
  @Test
  public void testAuthNoPassword() throws IOException, FcrepoOperationFailedException {
    final int status = 200;
    final URI uri = create(baseUrl);
    final ByteArrayEntity entity = new ByteArrayEntity(rdfXml.getBytes());

    testClient = new FcrepoClient("user", null, null, true);
    setField(testClient, "httpclient", mockHttpclient);
    entity.setContentType(RDF_XML);
    doSetupMockRequest(RDF_XML, entity, status);

    final FcrepoResponse response = testClient.get(uri, RDF_XML, null);

    assertEquals(response.getUrl(), uri);
    assertEquals(response.getStatusCode(), status);
    assertEquals(response.getContentType(), RDF_XML);
    assertEquals(response.getLocation(), null);
    assertEquals(IOUtils.toString(response.getBody()), rdfXml);
  }
  /**
   * Build the HttpEntity to be sent to the Service as part of (POST) request. Creates a off-memory
   * {@link FileExposingFileEntity} or a regular in-memory {@link ByteArrayEntity} depending on if
   * the request OutputStream fit into memory when built by calling {@link
   * #writeRequestBodyToOutputStream(ClientRequest)}.
   *
   * @param request -
   * @return - the built HttpEntity
   * @throws IOException -
   */
  protected HttpEntity buildEntity(final ClientRequest request) throws IOException {
    HttpEntity entityToBuild = null;
    DeferredFileOutputStream memoryManagedOutStream = writeRequestBodyToOutputStream(request);

    if (memoryManagedOutStream.isInMemory()) {
      ByteArrayEntity entityToBuildByteArray =
          new ByteArrayEntity(memoryManagedOutStream.getData());
      entityToBuildByteArray.setContentType(
          new BasicHeader(HTTP.CONTENT_TYPE, request.getBodyContentType().toString()));
      entityToBuild = entityToBuildByteArray;
    } else {
      File requestBodyFile = memoryManagedOutStream.getFile();
      requestBodyFile.deleteOnExit();
      entityToBuild =
          new FileExposingFileEntity(
              memoryManagedOutStream.getFile(), request.getBodyContentType().toString());
    }

    return entityToBuild;
  }
示例#12
0
  protected void handleException(HttpException var1, HttpResponse var2) {
    if (var1 instanceof MethodNotSupportedException) {
      var2.setStatusCode(501);
    } else if (var1 instanceof UnsupportedHttpVersionException) {
      var2.setStatusCode(505);
    } else if (var1 instanceof ProtocolException) {
      var2.setStatusCode(400);
    } else {
      var2.setStatusCode(500);
    }

    String var4 = var1.getMessage();
    String var3 = var4;
    if (var4 == null) {
      var3 = var1.toString();
    }

    ByteArrayEntity var5 = new ByteArrayEntity(EncodingUtils.getAsciiBytes(var3));
    var5.setContentType("text/plain; charset=US-ASCII");
    var2.setEntity(var5);
  }
 protected HttpEntity marshal(Object object) {
   log.debug("marshal() object:{}", object);
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     synchronized (marshaller) {
       marshaller.marshal(object, baos);
     }
     baos.flush();
     ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
     entity.setContentType(APP_XML);
     if (log.isTraceEnabled()) {
       log.trace("marshal() raw HttpsXmlChargify request:{}", new String(baos.toByteArray()));
     }
     log.debug("marshal() returning entity:{}", entity);
     return entity;
   } catch (JAXBException e) {
     log.error("marshal() caught exception", e);
     throw new RuntimeException(e);
   } catch (IOException e) {
     log.error("marshal() caught exception", e);
     throw new RuntimeException(e);
   }
 }
示例#14
0
  /**
   * This test case executes a series of simple POST requests using the 'expect: continue'
   * handshake.
   */
  @Test
  public void testHttpPostsWithExpectContinue() throws Exception {

    final int reqNo = 20;

    final Random rnd = new Random();

    // Prepare some random data
    final List<byte[]> testData = new ArrayList<byte[]>(reqNo);
    for (int i = 0; i < reqNo; i++) {
      final int size = rnd.nextInt(5000);
      final byte[] data = new byte[size];
      rnd.nextBytes(data);
      testData.add(data);
    }

    // Initialize the server-side request handler
    this.server.registerHandler(
        "*",
        new HttpRequestHandler() {

          public void handle(
              final HttpRequest request, final HttpResponse response, final HttpContext context)
              throws HttpException, IOException {

            if (request instanceof HttpEntityEnclosingRequest) {
              final HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity();
              final byte[] data = EntityUtils.toByteArray(incoming);

              final ByteArrayEntity outgoing = new ByteArrayEntity(data);
              outgoing.setChunked(true);
              response.setEntity(outgoing);
            } else {
              final StringEntity outgoing = new StringEntity("No content");
              response.setEntity(outgoing);
            }
          }
        });

    this.server.start();

    // Activate 'expect: continue' handshake
    final DefaultBHttpClientConnection conn = client.createConnection();
    final HttpHost host = new HttpHost("localhost", this.server.getPort());

    try {
      for (int r = 0; r < reqNo; r++) {
        if (!conn.isOpen()) {
          client.connect(host, conn);
        }

        final BasicHttpEntityEnclosingRequest post =
            new BasicHttpEntityEnclosingRequest("POST", "/");
        final byte[] data = testData.get(r);
        final ByteArrayEntity outgoing = new ByteArrayEntity(data);
        outgoing.setChunked(true);
        post.setEntity(outgoing);

        final HttpResponse response = this.client.execute(post, host, conn);
        final byte[] received = EntityUtils.toByteArray(response.getEntity());
        final byte[] expected = testData.get(r);

        Assert.assertEquals(expected.length, received.length);
        for (int i = 0; i < expected.length; i++) {
          Assert.assertEquals(expected[i], received[i]);
        }
        if (!this.client.keepAlive(response)) {
          conn.close();
        }
      }

      // Verify the connection metrics
      final HttpConnectionMetrics cm = conn.getMetrics();
      Assert.assertEquals(reqNo, cm.getRequestCount());
      Assert.assertEquals(reqNo, cm.getResponseCount());
    } finally {
      conn.close();
      this.server.shutdown();
    }
  }
示例#15
0
文件: n.java 项目: hardik099/work
 public static int a(Context paramContext, JSONObject paramJSONObject, boolean paramBoolean)
 {
   String str1 = ac.a(2);
   if (!URLUtil.isHttpUrl(str1))
   {
     x.f();
     return -1;
   }
   HttpPost localHttpPost = new HttpPost(str1);
   BasicHttpParams localBasicHttpParams = new BasicHttpParams();
   HttpConnectionParams.setConnectionTimeout(localBasicHttpParams, 30000);
   HttpConnectionParams.setSoTimeout(localBasicHttpParams, 30000);
   DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(localBasicHttpParams);
   if (paramContext.getPackageManager().checkPermission(z[25], paramContext.getPackageName()) == 0)
   {
     NetworkInfo localNetworkInfo = ((ConnectivityManager)paramContext.getSystemService(z[30])).getActiveNetworkInfo();
     if ((localNetworkInfo != null) && (localNetworkInfo.getType() != 1))
     {
       String str5 = localNetworkInfo.getExtraInfo();
       if ((str5 != null) && ((str5.equals(z[22])) || (str5.equals(z[19])) || (str5.equals(z[33])))) {
         localDefaultHttpClient.getParams().setParameter(z[34], new HttpHost(z[24], 80));
       }
     }
   }
   String str2 = "";
   if (paramJSONObject != null) {
     str2 = paramJSONObject.toString();
   }
   if (ai.a(str2))
   {
     x.c();
     return -2;
   }
   localHttpPost.addHeader(z[28], z[31]);
   localHttpPost.addHeader(z[26], z[21]);
   localHttpPost.addHeader(z[35], z[21]);
   localHttpPost.addHeader(z[23], a.v(paramContext));
   String str3;
   int i;
   if (str2 == null)
   {
     str3 = ac.a(paramContext);
     if (!ai.a(str3)) {
       break label343;
     }
     x.c();
     i = 0;
   }
   for (;;)
   {
     if (i != 0) {
       break label405;
     }
     x.c();
     return -3;
     str3 = ac.a(paramContext, str2, 2);
     break;
     label343:
     String str4 = ac.b(str3);
     if (ai.a(str4))
     {
       x.c();
       i = 0;
     }
     else
     {
       localHttpPost.addHeader(z[29], z[32] + str4);
       i = 1;
     }
   }
   try
   {
     label405:
     byte[] arrayOfByte1 = str2.getBytes(z[10]);
     ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
     GZIPOutputStream localGZIPOutputStream = new GZIPOutputStream(localByteArrayOutputStream);
     localGZIPOutputStream.write(arrayOfByte1);
     localGZIPOutputStream.close();
     byte[] arrayOfByte2 = localByteArrayOutputStream.toByteArray();
     localByteArrayOutputStream.close();
     ByteArrayEntity localByteArrayEntity = new ByteArrayEntity(arrayOfByte2);
     localByteArrayEntity.setContentEncoding(z[21]);
     localHttpPost.setEntity(localByteArrayEntity);
     try
     {
       int j = localDefaultHttpClient.execute(localHttpPost).getStatusLine().getStatusCode();
       new StringBuilder(z[20]).append(j).toString();
       x.c();
       switch (j)
       {
       default: 
         if (j / 100 == 5) {
           return 500;
         }
       case 401: 
         x.e();
         return 401;
       case 404: 
         return 404;
       case 429: 
         return 429;
         return -5;
       }
     }
     catch (ClientProtocolException localClientProtocolException)
     {
       new StringBuilder(z[27]).append(localClientProtocolException.getMessage()).toString();
       x.f();
       return -1;
     }
     catch (IOException localIOException2)
     {
       for (;;)
       {
         new StringBuilder(z[36]).append(localIOException2.getMessage()).toString();
         x.f();
       }
     }
     return 200;
   }
   catch (UnsupportedEncodingException localUnsupportedEncodingException)
  /** Do in background post. */
  private void doInBackgroundPost() {
    Log.i(getClass().getSimpleName(), "start-background task");

    if (!isDBSync) {
      hashMap = new Hashtable<String, List<BluetoothDeviceModel>>();
      hashMap.put("deviceList", bluetoothDeviceList);
    } else {
      hashMap2 = new Hashtable<String, String>();
      hashMap2.put("latestUpdatedDate", latestUpdatedDate);
      //			hashMap2 = new Hashtable<String, List<KNNModel>>();
      //			hashMap2.put("dbLocalList", localDBList);
    }

    try {
      HttpParams httpParams = new BasicHttpParams();

      // set parameters for connection
      HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
      HttpConnectionParams.setConnectionTimeout(httpParams, networkConnectionTimeout_ms);
      HttpConnectionParams.setSoTimeout(httpParams, networkConnectionTimeout_ms);
      DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);

      // create post method
      HttpPost postMethod = new HttpPost(serviceUri);

      // create request entity
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(baos);
      if (!isDBSync) {
        oos.writeObject(hashMap);
      } else {
        oos.writeObject(hashMap2);
      }
      ByteArrayEntity requestEntity = new ByteArrayEntity(baos.toByteArray());
      requestEntity.setContentType(MIMETypeConstantsIF.BINARY_TYPE);

      // associating entity with method
      postMethod.setEntity(requestEntity);

      // response
      httpClient.execute(
          postMethod,
          new ResponseHandler<Void>() {

            @SuppressWarnings("unchecked")
            public Void handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {
              HttpEntity responseEntity = response.getEntity();

              if (responseEntity != null) {

                try {
                  byte[] data = EntityUtils.toByteArray(responseEntity);
                  ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
                  dataFromServlet = (Hashtable<DataKeys, Serializable>) ois.readObject();
                } catch (ClassNotFoundException e) {
                  Log.e(getClass().getSimpleName(), "Processing error ", e);
                }
              } else {
                throw new IOException(
                    new StringBuffer()
                        .append("HTTP response: ")
                        .append(response.getStatusLine())
                        .toString());
              }
              return null;
            }
          });
    } catch (Exception e) {
      ex = e;
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      e.printStackTrace(pw);
      Log.e(getClass().getSimpleName(), sw.getBuffer().toString(), e);
    }
  }
示例#17
0
 @Override
 public void writeTo(final OutputStream outstream) throws IOException {
   super.writeTo(new CountingOutputStream(outstream, this.listener));
 }
示例#18
0
  private HttpResponse phaRequestPart1(
      String reqMeth,
      String reletivePath,
      Object queryString,
      String phaToken,
      String phaTokenSecret,
      Object requestBody, // String or byte[]
      String contentType,
      Map<String, Object> options)
      throws IndivoClientException {

    String consumerToken = null;
    String consumerSecret = null;
    String foreignURL = null;
    Object indivoInstallation = options.get("indivoInstallation");
    if (indivoInstallation != null) {
      if (!(indivoInstallation instanceof String[])) {
        throw new IndivoClientException(
            "indivoInstallation option must be of type String[] with lenght == 3.  Was: "
                + indivoInstallation.getClass().getName());
      }
      String[] indivoInstallation0 = (String[]) indivoInstallation;
      if (indivoInstallation0.length != 3) {
        throw new IndivoClientException(
            "indivoInstallation option must be a String array with length 3. Length is: "
                + indivoInstallation0.length);
      }
      foreignURL = indivoInstallation0[0];
      consumerToken = indivoInstallation0[1];
      consumerSecret = indivoInstallation0[2];
    }

    logger.info(
        "consumerToken, consumerSecret, foreignURL: "
            + consumerToken
            + ", "
            + consumerSecret
            + ", "
            + foreignURL);
    String displayQS = "null";
    if (queryString != null) {
      displayQS = queryString.getClass().getName() + " " + queryString;
    }
    ;

    logger.info(
        "reletivePath, queryString, requestXmlOrParams: "
            + reletivePath
            + ",  "
            + displayQS
            + '\n'
            + requestBody
            + "\n\n");
    String queryString0;
    if (queryString == null
        || ((queryString instanceof String) && ((String) queryString).length() == 0)) {
      queryString0 = "";
    } else if (queryString instanceof String) {
      String qsString = (String) queryString;
      if (qsString.indexOf('=') < 1) {
        throw new IndivoClientException(
            "unexpected queryString, did not have any key/value delimiter of '=': " + queryString);
      }
      queryString0 = qsString;
      logger.info("queryString0 = qsString = " + qsString);
    } else if (queryString instanceof Map) {
      StringBuffer qsBuff = new StringBuffer();
      Map qsMap = (Map) queryString;
      Iterator iter = qsMap.keySet().iterator();
      while (iter.hasNext()) {
        if (qsBuff.length() > 0) {
          qsBuff.append('&');
        }

        Object keyObj = iter.next();
        if (!(keyObj instanceof String)) {
          throw new IndivoClientException(
              "queryString map key of unexpected type: "
                  + keyObj.getClass().getName()
                  + " -- "
                  + keyObj);
        }
        String key = (String) keyObj;

        Object valueObj = qsMap.get(key);
        try {
          if (valueObj instanceof String) {
            qsBuff.append(
                URLEncoder.encode(key, "UTF-8")
                    + '='
                    + URLEncoder.encode((String) valueObj, "UTF-8"));
          } else if (valueObj instanceof String[]) {
            String[] valueArr = (String[]) valueObj;
            for (int ii = 0; ii < valueArr.length; ii++) {
              qsBuff.append(
                  URLEncoder.encode(key, "UTF-8") + '=' + URLEncoder.encode(valueArr[ii], "UTF-8"));
            }
          } else {
            throw new IndivoClientException(
                "queryString map value of unexpected type: "
                    + valueObj.getClass().getName()
                    + " -- "
                    + valueObj);
          }
        } catch (java.io.UnsupportedEncodingException uee) {
          throw new IndivoClientException(uee);
        }
      }
      queryString0 = qsBuff.toString();
    } else {
      throw new IndivoClientException(
          "queryString not String or Map, type is: " + queryString.getClass().getName());
    }

    String baseURL0 = defaultBaseURL;
    if (foreignURL != null) {
      baseURL0 = foreignURL;
    }

    String consumerKey0 = defaultConsumerKey;
    String consumerSecret0 = defaultConsumerSecret;
    if (consumerToken != null) {
      consumerKey0 = consumerToken;
      consumerSecret0 = consumerSecret;
    }

    logger.info(
        " -- baseURL0: "
            + baseURL0
            + " -- reletivePath: "
            + reletivePath
            + " -- queryString: "
            + queryString0);

    String phaURLString = baseURL0 + reletivePath;
    if (queryString0.length() > 0) {
      phaURLString += "?" + queryString0;
    }

    /* FIXME temp for test*/
    // System.out.println(phaURLString); if (requestBody != null) { System.out.println(requestBody);
    // }

    if (requestBody != null) {
      if (requestBody instanceof String) {
        if (((String) requestBody).length() > 0) {
          if (contentType == null || contentType.length() == 0) {
            throw new IndivoClientException("contentType must be provided for request body");
          }
        }
      } else if ((requestBody instanceof Byte[] && ((Byte[]) requestBody).length > 0)
          || (requestBody instanceof byte[] && ((byte[]) requestBody).length > 0)) {
        if (contentType == null || contentType.length() == 0) {
          throw new IndivoClientException("contentType must be provided for request body");
        }
      } else {
        throw new IndivoClientException(
            "requestBody must be either String or Byte[] or byte[], was: "
                + requestBody.getClass().getName());
      }
    } else if (contentType != null && contentType.length() > 0) {
      throw new IndivoClientException("content type provided without requestBody: " + contentType);
    }

    HttpUriRequest hcRequest = null;

    // String requestXmlOrParams0 = null;
    if (requestBody == null) {
      requestBody = "";
    }

    logger.info("reqMeth: " + reqMeth);
    try {
      if (reqMeth.equals("PUT") || reqMeth.equals("POST")) {
        if (reqMeth.equals("PUT")) {
          hcRequest = new HttpPut(phaURLString);
        } else {
          hcRequest = new HttpPost(phaURLString);
        }

        byte[] requestBodyB = null;
        if (requestBody instanceof String) {
          String requestBodyStr = (String) requestBody;
          if (requestBodyStr.startsWith("<?xml")) {
            String[] parsedProlog = getEncoding(requestBodyStr);
            if (parsedProlog.length == 3 && (!parsedProlog[1].toUpperCase().equals("UTF-8"))) {
              requestBodyStr = parsedProlog[0] + "UTF-8" + parsedProlog[1];
              logger.info("changing prolog from: " + parsedProlog[1] + " to: " + "UTF-8");
              requestBodyStr = parsedProlog[0] + "UTF-8" + parsedProlog[2];
            }
          }

          // System.out.println("requestBodyStr: " + requestBodyStr);
          requestBodyB = requestBodyStr.getBytes("UTF-8");
        } else if (requestBody instanceof byte[]) {
          requestBodyB = (byte[]) requestBody;
        } else { // requestBody instanceof Byte[]
          requestBodyB = new byte[((Byte[]) requestBody).length];
          for (int ii = 0; ii < ((Byte[]) requestBody).length; ii++) {
            requestBodyB[ii] = ((Byte[]) requestBody)[ii];
          }
        }
        ByteArrayEntity bae = new ByteArrayEntity(requestBodyB);
        bae.setContentType(contentType);
        ((HttpEntityEnclosingRequestBase) hcRequest).setEntity(bae);
        //                hcRequest.addHeader("Content-Type",contentType);
      } else if (reqMeth.equals("GET")) {
        hcRequest = new HttpGet(phaURLString);
      } else if (reqMeth.equals("DELETE")) {
        hcRequest = new HttpDelete(phaURLString);
      }
    } catch (java.io.UnsupportedEncodingException uee) {
      throw new IndivoClientException(uee);
    }

    // in case of form-url-encoded, will signpost know to look at Content-Type header and entity??

    logger.info("pre signWithSignpost");
    signWithSignpost(hcRequest, consumerKey0, consumerSecret0, phaToken, phaTokenSecret);
    logger.info("post signWithSignpost");

    hcRequest.addHeader("Accept", "text/plain,application/xml"); // don't be mistaken for a browser
    logger.info("post signWithSignpost 1");

    AbstractHttpClient httpClient = new DefaultHttpClient();
    HttpParams httpParams0 = httpClient.getParams();
    logger.info("post signWithSignpost 2");

    Object connectionTimeout = options.get("connectionTimeout");
    Object socketTimeout = options.get("socketTimeout");
    logger.info("post signWithSignpost 3");
    if (connectionTimeout == null) {
      connectionTimeout = defaultHttpTimeout;
    }
    if (socketTimeout == null) {
      socketTimeout = defaultHttpTimeout;
    }
    logger.info("post signWithSignpost 4");

    if (!((socketTimeout instanceof Integer) && (connectionTimeout instanceof Integer))) {
      throw new IndivoClientException(
          "socketTimeout and connectionTimeout options must be ingeters. "
              + "sockenTimeout was "
              + socketTimeout.getClass().getName()
              + ", and connectionTimeout was "
              + connectionTimeout.getClass().getName());
    }
    logger.info("about to set CONNECTION_TIMEOUT");

    httpParams0 =
        httpParams0.setIntParameter(
            CoreConnectionPNames.CONNECTION_TIMEOUT, (Integer) connectionTimeout);
    httpParams0 =
        httpParams0.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, (Integer) socketTimeout);
    httpClient.setParams(httpParams0);

    HttpResponse httpResponse = null;
    //        StatusLine statusLine = null;
    //        InputStream istrm = null;
    org.apache.http.Header[] allheaders = hcRequest.getAllHeaders();
    StringBuffer allheadersSB = new StringBuffer("\nall request headers:");
    for (int ii = 0; ii < allheaders.length; ii++) {
      allheadersSB.append("\n" + allheaders[ii].getName() + " : " + allheaders[ii].getValue());
    }
    logger.info("request: " + hcRequest.getMethod() + " " + hcRequest.getURI() + allheadersSB);
    try {
      httpResponse = httpClient.execute(hcRequest);
    } catch (java.net.ConnectException conE) {
      conE.printStackTrace();
      logger.warn("connectionTimeout, socketTimeout: " + connectionTimeout + ", " + socketTimeout);
      throw new IndivoClientConnectException(
          "connectionTimeout, socketTimeout: " + connectionTimeout + ", " + socketTimeout, conE);
    } catch (Exception excp) {
      excp.printStackTrace();
      logger.warn("phaRequestPart1 exception");
      throw new IndivoClientException(
          "connectionTimeout, socketTimeout: " + connectionTimeout + ", " + socketTimeout, excp);
    }

    return httpResponse;
  }
示例#19
0
  public static void main(String[] args) {

    DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.createHttpClient();

    int day = 1;
    String time = "dinner";

    while (true) {
      try {

        client.addResponseInterceptor(
            new HttpResponseInterceptor() {

              public void process(final HttpResponse response, final HttpContext context)
                  throws HttpException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                  Header ceheader = entity.getContentEncoding();
                  if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++) {
                      if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                      }
                    }
                  }
                }
              }
            });

        HttpPost post =
            new HttpPost("https://disneyworld.disney.go.com/activities/dining-availability");

        post.setHeader("Accept", "*/*");
        post.setHeader("Accept-Encoding", "gzip,deflate,sdch");
        post.setHeader("Accept-Language", "en-US,en;q=0.8");
        post.setHeader("Connection", "keep-alive");
        // post.setHeader("Content-Length", "178");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");
        post.setHeader(
            "Cookie",
            "optimizelyEndUserId=oeu1358558437847r0.07084921281784773; __qca=P0-661515119-1358558438978; dolWA30=1362951732650; grvinsights=ee419b7b50b4f796e86088c3b1d2ad42; cto_firstUrl=\"http://disneyrewards.com/perks/disneyland-perks\"; cto_visitorId=1377887977144-9354867790880; cto_firstPageName=\"dcore:drv:perks:disneyland-perks\"; cto_sessionCount=1; cto_firstRefUrl=na; ctoTimeStamp=1387999595863; backplane-id=41231508470D4B238A7306575348FC41; bp_channel_id=https%3A%2F%2Fapi.echoenabled.com%2Fv1%2Fbus%2Fespn.go.com%2Fchannel%2F41231508470D4B238A7306575348FC41; fbm_116656161708917=base_domain=.go.com; rampenableCheckoutGuestPoc_A=%7B%22enableCheckoutGuestPoc%22%3Atrue%7D; analytics_targus=074%3B2978363885011DB0%7C6000010F800014AC; s_fid=52C9B90BC5607FB9-09F500455ED40B17; gi=usa|mo|kansas city|cable|39.009|-94.402|64118|f02fc4f4; rememberme=%7B%22name%22%3A%22Greg%22%2C%22lastName%22%3A%22Meyer%22%2C%22avatar%22%3A%2217532228%22%2C%22swid%22%3A%22%7BACA6E4C3-4397-43EF-A4AD-259926923E09%7D%22%2C%22passiveId%22%3A%2259f894315e2a19e7402e67fe4c6ff747da4e010fe12261eae24d14c73be8a8c57ccad22feb6201c1d8c4dde74475121d59bb112697d7f5753362f6c5eff25a68%22%2C%22email%22%3A%22kmeyer%40kc.rr.com%22%7D; SWID=ACA6E4C3-4397-43EF-A4AD-259926923E09; GEOLOCATION_jar=%7B%22region%22%3A%22missouri%22%2C%22country%22%3A%22united+states%22%7D; roomForm_jar=%7B%22checkInDate%22%3A%222014-09-01%22%2C%22checkOutDate%22%3A%222014-09-08%22%2C%22numberOfAdults%22%3A%222%22%2C%22numberOfChildren%22%3A%221%22%2C%22accessible%22%3A%220%22%2C%22resort%22%3A%2280010394%3BentityType%3Dresort%22%2C%22kid1%22%3A%2216%22%7D; currentOffer_jar=%7B%22currentOffer%22%3A%22resort-stay-dining%22%7D; 55170107-VID=53301077421770; optimizelySegments=%7B%22166049822%22%3A%22none%22%2C%22166646996%22%3A%22false%22%2C%22167330480%22%3A%22search%22%2C%22167351530%22%3A%22gc%22%2C%22173942781%22%3A%22gc%22%2C%22174819705%22%3A%22false%22%2C%22175220085%22%3A%22search%22%2C%22175226102%22%3A%22referral%22%2C%22175226103%22%3A%22none%22%2C%22175370703%22%3A%22false%22%2C%22175404369%22%3A%22none%22%2C%22175412291%22%3A%22gc%22%2C%22310954789%22%3A%22none%22%2C%22311043393%22%3A%22false%22%2C%22311047346%22%3A%22gc%22%2C%22311052307%22%3A%22referral%22%2C%22793783561%22%3A%22true%22%2C%22806111078%22%3A%22none%22%2C%22806950111%22%3A%22desktop%22%7D; optimizelyBuckets=%7B%7D; CRBLM=CBLM-001:AAAAAAABBGwAAAAB; CRBLM_LAST_UPDATE=1400616530:ACA6E4C3-4397-43EF-A4AD-259926923E09; PHPSESSID=oq7t0rqmdj9j4lb99b97r33vq3; CART-wdw_jar=%7B%22cartId%22%3A%22124935657330-9131021-6107974-2755370%22%7D; mbox=level#20#1403208529|PC#1391624422331-680398.17_31#1408406023|traffic#false#1407237700|check#true#1400630083|session#1400630022656-797538#1400631883; wdpro_seen_cmps=/55541/%2C/55542/%2C/56321/%2C/53949/; pep_oauth_token=BpZ7TgrYTjMmmNfOJcYmNA; boomr_rt=cl=1400630030984&nu=https%3A%2F%2Fdisneyworld.disney.go.com%2Fdining%2Fmagic-kingdom%2Fbe-our-guest-restaurant%2F%23; localeCookie_jar=%7B%22contentLocale%22%3A%22en_US%22%2C%22precedence%22%3A0%2C%22version%22%3A%221%22%7D; WDPROView=%7B%22version%22%3A2%2C%22preferred%22%3A%7B%22device%22%3A%22desktop%22%2C%22screenWidth%22%3A250%2C%22screenHeight%22%3A150%2C%22screenDensity%22%3A1%7D%2C%22deviceInfo%22%3A%7B%22device%22%3A%22desktop%22%2C%22screenWidth%22%3A250%2C%22screenHeight%22%3A150%2C%22screenDensity%22%3A1%7D%7D; s_vi=[CS]v1|2978363885011DB0-6000010F800014AC[CE]; s_pers=%20s_cpm%3D%255B%255B'SOC-DPFY14Q2EpcotInternationalFood'%252C'1392899303875'%255D%252C%255B'SOC-DPFY14Q2EpcotInternationalFood'%252C'1392899304121'%255D%252C%255B'SOC-DPFY14Q2EpcotInternationalFood'%252C'1392899304679'%255D%252C%255B'SOC-DPFY14Q2EpcotInternationalFood'%252C'1392899310315'%255D%252C%255B'SOC-DPFY14Q2EpcotInternationalFood'%252C'1392899314146'%255D%255D%7C1550665714146%3B%20s_c20%3D1397045509015%7C1491653509015%3B%20s_c20_s%3DMore%2520than%25207%2520days%7C1397047309015%3B%20s_c24%3D1400616538424%7C1495224538424%3B%20s_c24_s%3DLess%2520than%25201%2520day%7C1400618338424%3B%20s_gpv_pn%3Dwdpro%252Fwdw%252Fus%252Fen%252Ftools%252Ffinder%252Fdining%252Fmagickingdom%252Fbeourguestrestaurant%7C1400631862919%3B; s_sess=%20s_cc%3Dtrue%3B%20prevPageLoadTime%3Dwdpro%252Fwdw%252Fus%252Fen%252Ftools%252Ffinder%252Fdining%252Fmagickingdom%252Fbeourguestrestaurant%257C5.4%3B%20s_ppv%3D-%252C48%252C45%252C1167%3B%20s_wdpro_lid%3D%3B%20s_sq%3D%3B");
        post.setHeader("Host", "disneyworld.disney.go.com");
        post.setHeader("Origin", "https://disneyworld.disney.go.com");
        post.setHeader(
            "Referer",
            "https://disneyworld.disney.go.com/dining/magic-kingdom/be-our-guest-restaurant/");
        post.setHeader(
            "User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36");
        post.setHeader("X-Requested-With", "XMLHttpRequest");

        String content = getRequestContent(day, time);

        final ByteArrayEntity entity = new ByteArrayEntity(content.getBytes());
        entity.setContentType(MediaType.APPLICATION_JSON);
        entity.setContentEncoding("UTF-8");
        post.setEntity(entity);

        HttpResponse response = client.execute(post);

        HttpEntity responseEntity = response.getEntity();

        String responseContent = new String(IOUtils.toByteArray(responseEntity.getContent()));

        System.out.print("Availability for Sept " + day + " at " + time + "\r\n\r\n\r\n");
        System.out.println(responseContent);
        System.out.print("\r\n\r\n-----------------------------------------------\r\n\r\n");

        if (!responseContent.contains("No tables")) System.exit(0);

        if (time.equalsIgnoreCase("dinner")) time = "4";
        else {
          time = "dinner";

          ++day;
          if (day > 8) day = 1;
        }
        Thread.currentThread().sleep(500);

        responseEntity.getContent().close();

      } catch (Exception e) {
        // e.printStackTrace();
      }
    }
  }
示例#20
0
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    listenerCallBack.fireOnRequest(project, request, response);
    if (response.isCommitted()) {
      return;
    }

    ExtendedHttpMethod method;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET")) {
      method = new ExtendedGetMethod();
    } else if (httpRequest.getMethod().equals("POST")) {
      method = new ExtendedPostMethod();
    } else if (httpRequest.getMethod().equals("PUT")) {
      method = new ExtendedPutMethod();
    } else if (httpRequest.getMethod().equals("HEAD")) {
      method = new ExtendedHeadMethod();
    } else if (httpRequest.getMethod().equals("OPTIONS")) {
      method = new ExtendedOptionsMethod();
    } else if (httpRequest.getMethod().equals("TRACE")) {
      method = new ExtendedTraceMethod();
    } else if (httpRequest.getMethod().equals("PATCH")) {
      method = new ExtendedPatchMethod();
    } else {
      method = new ExtendedGenericMethod(httpRequest.getMethod());
    }

    method.setDecompress(false);

    ByteArrayOutputStream requestBody = null;
    if (method instanceof HttpEntityEnclosingRequest) {
      requestBody = Tools.readAll(request.getInputStream(), 0);
      ByteArrayEntity entity = new ByteArrayEntity(requestBody.toByteArray());
      entity.setContentType(request.getContentType());
      ((HttpEntityEnclosingRequest) method).setEntity(entity);
    }

    // for this create ui server and port, properties.
    JProxyServletWsdlMonitorMessageExchange capturedData =
        new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getServerName());
    capturedData.setRequestMethod(httpRequest.getMethod());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setHttpRequestParameters(httpRequest);
    capturedData.setQueryParameters(httpRequest.getQueryString());
    capturedData.setTargetURL(httpRequest.getRequestURL().toString());

    //		CaptureInputStream capture = new CaptureInputStream( httpRequest.getInputStream() );

    // check connection header
    String connectionHeader = httpRequest.getHeader("Connection");
    if (connectionHeader != null) {
      connectionHeader = connectionHeader.toLowerCase();
      if (!connectionHeader.contains("keep-alive") && !connectionHeader.contains("close")) {
        connectionHeader = null;
      }
    }

    // copy headers
    boolean xForwardedFor = false;
    @SuppressWarnings("unused")
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String hdr = (String) headerNames.nextElement();
      String lhdr = hdr.toLowerCase();

      if (dontProxyHeaders.contains(lhdr)) {
        continue;
      }
      if (connectionHeader != null && connectionHeader.contains(lhdr)) {
        continue;
      }

      Enumeration<?> vals = httpRequest.getHeaders(hdr);
      while (vals.hasMoreElements()) {
        String val = (String) vals.nextElement();
        if (val != null) {
          method.setHeader(lhdr, val);
          xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
        }
      }
    }

    // Proxy headers
    method.setHeader("Via", "SoapUI Monitor");
    if (!xForwardedFor) {
      method.addHeader("X-Forwarded-For", request.getRemoteAddr());
    }

    StringBuffer url = new StringBuffer("http://");
    url.append(httpRequest.getServerName());
    if (httpRequest.getServerPort() != 80) {
      url.append(":" + httpRequest.getServerPort());
    }

    if (httpRequest.getServletPath() != null) {
      url.append(httpRequest.getServletPath());
      try {
        method.setURI(new java.net.URI(url.toString().replaceAll(" ", "%20")));
      } catch (URISyntaxException e) {
        SoapUI.logError(e);
      }

      if (httpRequest.getQueryString() != null) {
        url.append("?" + httpRequest.getQueryString());
        try {
          method.setURI(new java.net.URI(url.toString()));
        } catch (URISyntaxException e) {
          SoapUI.logError(e);
        }
      }
    }

    method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    setProtocolversion(method, request.getProtocol());
    ProxyUtils.setForceDirectConnection(method.getParams());
    listenerCallBack.fireBeforeProxy(project, request, response, method);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
      if (httpState == null) {
        httpState = new BasicHttpContext();
      }
      HttpClientSupport.execute(method, httpState);
    } else {
      HttpClientSupport.execute(method);
    }

    // wait for transaction to end and store it.
    capturedData.stopCapture();

    capturedData.setRequest(requestBody == null ? null : requestBody.toByteArray());
    capturedData.setRawResponseBody(method.getResponseBody());
    capturedData.setResponseHeader(method.getHttpResponse());
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), requestBody));
    capturedData.setRawResponseData(getResponseToBytes(method, capturedData.getRawResponseBody()));
    byte[] decompressedResponseBody = method.getDecompressedResponseBody();
    capturedData.setResponseContent(
        decompressedResponseBody != null ? new String(decompressedResponseBody) : "");
    capturedData.setResponseStatusCode(
        method.hasHttpResponse() ? method.getHttpResponse().getStatusLine().getStatusCode() : null);
    capturedData.setResponseStatusLine(
        method.hasHttpResponse() ? method.getHttpResponse().getStatusLine().toString() : null);

    listenerCallBack.fireAfterProxy(project, request, response, method, capturedData);

    ((HttpServletResponse) response)
        .setStatus(
            method.hasHttpResponse()
                ? method.getHttpResponse().getStatusLine().getStatusCode()
                : null);

    if (!response.isCommitted()) {
      StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
      // capturedData = null;

      // copy headers to response
      HttpServletResponse httpServletResponse = (HttpServletResponse) response;
      for (Map.Entry<String, List<String>> headerEntry : responseHeaders.entrySet()) {
        for (String header : headerEntry.getValue()) {
          httpServletResponse.addHeader(headerEntry.getKey(), header);
        }
      }

      if (capturedData.getRawResponseBody() != null) {
        IO.copy(
            new ByteArrayInputStream(capturedData.getRawResponseBody()),
            httpServletResponse.getOutputStream());
      }
    }

    synchronized (this) {
      if (contentTypeMatches(method)) {
        listenerCallBack.fireAddMessageExchange(capturedData);
      }
    }
  }