@Override
    protected Boolean doInBackground(HashMap<String, String>... params) {
      SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
      // Load the saved accessToken
      Token accessToken =
          new Token(
              settings.getString("accessToken", null), settings.getString("accessSecret", null));
      OAuthService service =
          new ServiceBuilder()
              .provider(OpenStreetMapAPI.class)
              .apiKey("3rTM4by36P1CsMfiwZ1g58L1c1tZOpQWLUo591tx")
              .apiSecret("Cl2NKl6LFAvKqXpI7Kvccwyamdz80rHAXLruWhbG")
              .build();
      Toast.makeText(m_a, m_a.getResources().getString(R.string.add_loading), Toast.LENGTH_LONG)
          .show();
      /** Getting a changeset from the api */
      OAuthRequest changeset_request =
          new OAuthRequest(Verb.PUT, "http://api.openstreetmap.org/api/0.6/changeset/create");
      String changeset_payload =
          "<osm>\n"
              + "<changeset>\n"
              + "<tag k=\"created_by\" v=\"TakeABreak 1.5\"/>\n"
              + "</changeset>\n"
              + "</osm>";
      changeset_request.addPayload(changeset_payload);
      changeset_request.addHeader("Content-Length", Integer.toString(changeset_payload.length()));
      changeset_request.addHeader("Content-Type", "text/xml");
      service.signRequest(accessToken, changeset_request); // the access token from step 4
      Response changeset_response = changeset_request.send();
      Log.d("TakeABreak", "Changeset: " + changeset_response.getBody());

      params[0].put("changeset", changeset_response.getBody());

      /** PUT-ing the change proper. */
      OAuthRequest request =
          new OAuthRequest(Verb.PUT, "http://api.openstreetmap.org/api/0.6/node/create");
      String payload = generatePayload(params[0]);
      request.addPayload(payload);
      request.addHeader("Content-Length", Integer.toString(payload.length()));
      request.addHeader("Content-Type", "text/xml");
      service.signRequest(accessToken, request); // the access token from step 4
      Response response = request.send();
      // Log.d("TakeABreak", response.toString());

      Iterator<Entry<String, String>> it = response.getHeaders().entrySet().iterator();
      Log.d("TakeABreak", response.getBody());
      // System.out.println(response.getBody());
      return response.isSuccessful();
      // return true;
    }
示例#2
0
  final <T extends ServerResponse> T doPost(CommandArguments args, Class<T> clazz, String url)
      throws FlickrException {
    try {
      OAuthRequest request = new OAuthRequest(Verb.POST, url);

      // check for proxy, use if available
      if (proxy != null) {
        request.setProxy(proxy);
      }

      for (Map.Entry<String, Object> param : args.getParameters().entrySet()) {
        if (param.getValue() instanceof String) {
          request.addQuerystringParameter(param.getKey(), (String) param.getValue());
        }
      }

      oauth.signRequest(request);

      MultipartEntity multipart = args.getBody(request.getOauthParameters());
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      multipart.writeTo(baos);

      request.addPayload(baos.toByteArray());
      request.addHeader("Content-type", multipart.getContentType().getValue());

      Response response = request.send();
      String body = response.getBody();

      return parseBody(args, clazz, body);

    } catch (IOException ex) {
      throw new UnsupportedOperationException("Error preparing multipart request", ex);
    }
  }
 private void addMultipartEntity(OAuthRequest request, MultipartEntity entity)
     throws N0ticeException {
   try {
     request.addPayload(extractMultpartBytes(entity));
   } catch (IOException e) {
     e.printStackTrace();
     throw new N0ticeException();
   }
 }
示例#4
0
  /*
   * posts an image to the users news feed
   * @param message to show
   * @param image as form data
   * @return the new image id if successful
   */
  public String publishPicture(String msg, Image image, String placeId) throws IOException {
    OAuthRequest request =
        new OAuthRequest(Verb.POST, "https://graph.facebook.com/v2.2/me/photos"); // request node
    request.addHeader("Authorization", "Bearer " + accessTokenString); // authentificate

    // check input to avoid error responses
    if (msg != null && image != null) {
      // facebook requires multipart post structure
      MultipartEntityBuilder builder = MultipartEntityBuilder.create();
      builder.addTextBody("message", msg); // description

      if (placeId != null && !"".equals(placeId)) {
        builder.addTextBody(
            "place", placeId); // add link to FabLab site if property is set in preferences
      }

      // convert image to bytearray and append to multipart
      BufferedImage bimage =
          new BufferedImage(
              image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
      Graphics2D bGr = bimage.createGraphics();
      bGr.drawImage(image, 0, 0, null);
      bGr.dispose();
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ImageIO.write(bimage, "png", baos);
      builder.addBinaryBody(msg, baos.toByteArray(), ContentType.MULTIPART_FORM_DATA, "test.png");

      // generate multipart byte stream and add to payload of post package
      HttpEntity multipart = builder.build();
      ByteArrayOutputStream multipartOutStream =
          new ByteArrayOutputStream((int) multipart.getContentLength());
      multipart.writeTo(multipartOutStream);
      request.addPayload(multipartOutStream.toByteArray());

      // set header of post package
      Header contentType = multipart.getContentType();
      request.addHeader(contentType.getName(), contentType.getValue());

      // send and response answer
      Response response = request.send();
      return response.getBody();
    } else {
      throw new RuntimeException(CONSTANTS.get(FACEBOOK_MESSAGE_IMG_NEEDED));
    }
  }
示例#5
0
  /**
   * Invoke an HTTP POST request on a remote host.
   *
   * @param path The request path
   * @param parameters The parameters (collection of Parameter objects)
   * @return The Response object
   */
  @Override
  public com.flickr4java.flickr.Response post(
      String path, Map<String, Object> parameters, String sharedSecret, boolean multipart) {

    OAuthRequest request = new OAuthRequest(Verb.POST, API_HOST + path);

    if (multipart) {
      buildMultipartRequest(parameters, request);
    } else {
      buildNormalPostRequest(parameters, request);
    }

    RequestContext requestContext = RequestContext.getRequestContext();
    Auth auth = requestContext.getAuth();
    if (auth != null) {
      Token requestToken = new Token(auth.getToken(), auth.getTokenSecret());
      OAuthService service = createOAuthService(parameters, sharedSecret);
      service.signRequest(requestToken, request);
    }

    if (multipart) {
      // Ensure all parameters (including oauth) are added to payload so signature matches
      parameters.putAll(request.getOauthParameters());
      request.addPayload(buildMultipartBody(parameters, getMultipartBoundary()));
    }

    if (proxyAuth) {
      request.addHeader("Proxy-Authorization", "Basic " + getProxyCredentials());
    }

    if (Flickr.debugRequest) {
      logger.debug("POST: " + request.getCompleteUrl());
    }

    org.scribe.model.Response scribeResponse = request.send();

    try {
      com.flickr4java.flickr.Response response = null;
      synchronized (mutex) {
        String strXml = scribeResponse.getBody();
        if (Flickr.debugStream) {
          logger.debug(strXml);
        }
        if (strXml.startsWith("oauth_problem=")) {
          throw new FlickrRuntimeException(strXml);
        }
        Document document = builder.parse(new InputSource(new StringReader(strXml)));
        response = (com.flickr4java.flickr.Response) responseClass.newInstance();
        response.parse(document);
      }
      return response;
    } catch (IllegalAccessException e) {
      throw new FlickrRuntimeException(e);
    } catch (InstantiationException e) {
      throw new FlickrRuntimeException(e);
    } catch (SAXException e) {
      throw new FlickrRuntimeException(e);
    } catch (IOException e) {
      throw new FlickrRuntimeException(e);
    }
  }