public void post(File file) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpPost httpPost = new HttpPost(uri);
    FileEntity fileEntity = new FileEntity(file, "binary/octet-stream");
    fileEntity.setChunked(true);
    httpPost.setEntity(fileEntity);

    HttpParams params = httpPost.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, DEFAULT_USER_AGENT);

    try {

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpPost);

      if (response.getStatusLine().getStatusCode() < 200
          || response.getStatusLine().getStatusCode() >= 300)
        throw new IOException(
            "bad status code, upload file " + response.getStatusLine().getStatusCode());

    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new IOException("Http error: " + e.getMessage());
    } finally {
      //
    }
  }
Esempio n. 2
0
  public void testPut() throws Exception {

    try {
      DefaultHttpClient httpClient = new DefaultHttpClient();
      String url = baseURL + "/rest/Pie";
      HttpPut putRequest = new HttpPut(url);
      File myFile = new File("Pie" + "XML.xml");
      if (!myFile.exists()) {
        testGet();
        myFile = new File("Pie" + "XML.xml");
        if (!myFile.exists()) return;
      }

      FileEntity input = new FileEntity(myFile);
      input.setContentType("application/xml");
      putRequest.setEntity(input);

      HttpResponse response = httpClient.execute(putRequest);

      if (response.getEntity() != null) {
        BufferedReader br =
            new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
          System.out.println(output);
        }
      }

      httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }
Esempio n. 3
0
  /**
   * Call method with optional parameters
   *
   * @param method name of method to call
   * @param params parameters to pass to method (may be null if method has no parameters)
   * @return deserialized method return value
   * @throws XMLRPCException
   */
  @SuppressWarnings("unchecked")
  private Object callXMLRPC(String method, Object[] params) throws XMLRPCException {
    File tempFile = null;
    try {
      // prepare POST body
      if (method.equals("wp.uploadFile")) {
        // String tempFilePath = Environment.getExternalStorageDirectory() + File.separator +
        // "b2evolution" + File.separator + "b2evo-" + System.currentTimeMillis() + ".xml";
        String tempFileName = "b2evo-" + System.currentTimeMillis();
        tempFile = File.createTempFile(tempFileName, null);

        if (!tempFile.exists() && !tempFile.mkdirs()) {
          throw new XMLRPCException("Path to file could not be created.");
        }

        FileWriter fileWriter = new FileWriter(tempFile);
        serializer.setOutput(fileWriter);

        serializer.startDocument(null, null);
        serializer.startTag(null, TAG_METHOD_CALL);
        // set method name
        serializer.startTag(null, TAG_METHOD_NAME).text(method).endTag(null, TAG_METHOD_NAME);
        if (params != null && params.length != 0) {
          // set method params
          serializer.startTag(null, TAG_PARAMS);
          for (int i = 0; i < params.length; i++) {
            serializer.startTag(null, TAG_PARAM).startTag(null, XMLRPCSerializer.TAG_VALUE);
            XMLRPCSerializer.serialize(serializer, params[i]);
            serializer.endTag(null, XMLRPCSerializer.TAG_VALUE).endTag(null, TAG_PARAM);
          }
          serializer.endTag(null, TAG_PARAMS);
        }
        serializer.endTag(null, TAG_METHOD_CALL);
        serializer.endDocument();

        fileWriter.flush();
        fileWriter.close();

        FileEntity fEntity = new FileEntity(tempFile, "text/xml; charset=\"UTF-8\"");
        fEntity.setContentType("text/xml");
        // fEntity.setChunked(true);
        postMethod.setEntity(fEntity);
      } else {
        StringWriter bodyWriter = new StringWriter();
        serializer.setOutput(bodyWriter);

        serializer.startDocument(null, null);
        serializer.startTag(null, TAG_METHOD_CALL);
        // set method name
        serializer.startTag(null, TAG_METHOD_NAME).text(method).endTag(null, TAG_METHOD_NAME);
        if (params != null && params.length != 0) {
          // set method params
          serializer.startTag(null, TAG_PARAMS);
          for (int i = 0; i < params.length; i++) {
            serializer.startTag(null, TAG_PARAM).startTag(null, XMLRPCSerializer.TAG_VALUE);
            if (method.equals("metaWeblog.editPost") || method.equals("metaWeblog.newPost")) {
              XMLRPCSerializer.serialize(serializer, params[i]);
            } else {
              XMLRPCSerializer.serialize(serializer, params[i]);
            }
            serializer.endTag(null, XMLRPCSerializer.TAG_VALUE).endTag(null, TAG_PARAM);
          }
          serializer.endTag(null, TAG_PARAMS);
        }
        serializer.endTag(null, TAG_METHOD_CALL);
        serializer.endDocument();

        HttpEntity entity = new StringEntity(bodyWriter.toString());
        // Log.i("b2evolution", bodyWriter.toString());
        postMethod.setEntity(entity);
      }

      // set timeout to 40 seconds, does it need to be set for both client and method?
      client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 40000);
      client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 40000);
      postMethod.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 40000);
      postMethod.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 40000);

      // execute HTTP POST request
      HttpResponse response = client.execute(postMethod);

      Log.i("b2evolution", "response = " + response.getStatusLine());
      // check status code
      int statusCode = response.getStatusLine().getStatusCode();

      deleteTempFile(method, tempFile);

      if (statusCode != HttpStatus.SC_OK) {
        throw new XMLRPCException(
            "HTTP status code: "
                + statusCode
                + " was returned. "
                + response.getStatusLine().getReasonPhrase());
      }

      // setup pull parser
      XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser();
      HttpEntity entity = response.getEntity();
      InputStream is = entity.getContent();

      // Many b2evolution configs can output junk before the xml response (php warnings for
      // example), this cleans it.
      int bomCheck = -1;
      int stopper = 0;
      while ((bomCheck = is.read()) != -1 && stopper <= 5000) {
        stopper++;
        String snippet = "";
        // 60 == '<' character
        if (bomCheck == 60) {
          for (int i = 0; i < 4; i++) {
            byte[] chunk = new byte[1];
            is.read(chunk);
            snippet += new String(chunk, "UTF-8");
          }
          if (snippet.equals("?xml")) {
            // it's all good, add xml tag back and start parsing
            String start = "<" + snippet;
            List<InputStream> streams =
                Arrays.asList(new ByteArrayInputStream(start.getBytes()), is);
            is = new SequenceInputStream(Collections.enumeration(streams));
            break;
          } else {
            // keep searching...
            List<InputStream> streams =
                Arrays.asList(new ByteArrayInputStream(snippet.getBytes()), is);
            is = new SequenceInputStream(Collections.enumeration(streams));
          }
        }
      }

      pullParser.setInput(is, "UTF-8");

      // lets start pulling...
      pullParser.nextTag();
      pullParser.require(XmlPullParser.START_TAG, null, TAG_METHOD_RESPONSE);

      pullParser.nextTag(); // either TAG_PARAMS (<params>) or TAG_FAULT (<fault>)
      String tag = pullParser.getName();
      if (tag.equals(TAG_PARAMS)) {
        // normal response
        pullParser.nextTag(); // TAG_PARAM (<param>)
        pullParser.require(XmlPullParser.START_TAG, null, TAG_PARAM);
        pullParser.nextTag(); // TAG_VALUE (<value>)
        // no parser.require() here since its called in XMLRPCSerializer.deserialize() below

        // deserialize result
        Object obj = XMLRPCSerializer.deserialize(pullParser);
        entity.consumeContent();
        return obj;
      } else if (tag.equals(TAG_FAULT)) {
        // fault response
        pullParser.nextTag(); // TAG_VALUE (<value>)
        // no parser.require() here since its called in XMLRPCSerializer.deserialize() below

        // deserialize fault result
        Map<String, Object> map = (Map<String, Object>) XMLRPCSerializer.deserialize(pullParser);
        String faultString = (String) map.get(TAG_FAULT_STRING);
        int faultCode = (Integer) map.get(TAG_FAULT_CODE);
        entity.consumeContent();
        throw new XMLRPCFault(faultString, faultCode);
      } else {
        entity.consumeContent();
        throw new XMLRPCException(
            "Bad tag <" + tag + "> in XMLRPC response - neither <params> nor <fault>");
      }
    } catch (XMLRPCException e) {
      // catch & propagate XMLRPCException/XMLRPCFault
      deleteTempFile(method, tempFile);
      throw e;
    } catch (Exception e) {
      // wrap any other Exception(s) around XMLRPCException
      deleteTempFile(method, tempFile);
      throw new XMLRPCException(e);
    }
  }