Example usage for org.apache.http.client.utils URLEncodedUtils parse

List of usage examples for org.apache.http.client.utils URLEncodedUtils parse

Introduction

In this page you can find the example usage for org.apache.http.client.utils URLEncodedUtils parse.

Prototype

public static List<NameValuePair> parse(final HttpEntity entity) throws IOException 

Source Link

Document

Returns a list of NameValuePair NameValuePairs as parsed from an HttpEntity .

Usage

From source file:Main.java

public static Map handleURLEncodedResponse(HttpResponse response) {
    Map<String, Charset> map = Charset.availableCharsets();
    Map<String, String> oauthResponse = new HashMap<String, String>();
    Set<Map.Entry<String, Charset>> set = map.entrySet();
    Charset charset = null;//from   w  w  w  . j av a 2  s .  co m
    HttpEntity entity = response.getEntity();

    System.out.println();
    System.out.println("********** URL Encoded Response Received **********");

    for (Map.Entry<String, Charset> entry : set) {
        System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
        if (entry.getKey().equalsIgnoreCase(HTTP.UTF_8)) {
            charset = entry.getValue();
        }
    }

    try {
        List<NameValuePair> list = URLEncodedUtils.parse(entity);
        for (NameValuePair pair : list) {
            System.out.println(String.format("  %s = %s", pair.getName(), pair.getValue()));
            oauthResponse.put(pair.getName(), pair.getValue());
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new RuntimeException("Could not parse URLEncoded Response");
    }

    return oauthResponse;
}

From source file:org.mobicents.servlet.restcomm.util.HttpUtils.java

public static Map<String, String> toMap(final HttpEntity entity) throws IllegalStateException, IOException {

    String contentType = null;//w ww  .  j a va  2  s . com
    String charset = null;

    contentType = EntityUtils.getContentMimeType(entity);
    charset = EntityUtils.getContentCharSet(entity);

    List<NameValuePair> parameters = null;
    if (contentType != null && contentType.equalsIgnoreCase(CONTENT_TYPE)) {
        parameters = URLEncodedUtils.parse(entity);
    } else {
        final String content = EntityUtils.toString(entity, HTTP.ASCII);
        if (content != null && content.length() > 0) {
            parameters = new ArrayList<NameValuePair>();
            URLEncodedUtils.parse(parameters, new Scanner(content), charset);
        }
    }

    final Map<String, String> map = new HashMap<String, String>();
    for (final NameValuePair parameter : parameters) {
        map.put(parameter.getName(), parameter.getValue());
    }
    return map;
}

From source file:org.whispercomm.c2dm4j.impl.C2dmHttpPostTest.java

@Test
public void entityContainsRegistrationId() throws IOException {
    List<NameValuePair> data = URLEncodedUtils.parse(post.getEntity());
    assertThat(data.contains(new BasicNameValuePair("registration_id", REGISTRATION_ID)), is(true));
}

From source file:org.whispercomm.c2dm4j.impl.C2dmHttpPostTest.java

@Test
public void entityContainsCollapseKey() throws IOException {
    List<NameValuePair> data = URLEncodedUtils.parse(post.getEntity());
    assertThat(data.contains(new BasicNameValuePair("collapse_key", COLLAPSE_KEY)), is(true));
}

From source file:org.whispercomm.c2dm4j.impl.C2dmHttpPostTest.java

@Test
public void entityContainsDelayWhileIdle() throws IOException {
    List<NameValuePair> data = URLEncodedUtils.parse(post.getEntity());
    assertThat(data.contains(new BasicNameValuePair("delay_while_idle", null)), is(true));
}

From source file:org.whispercomm.c2dm4j.impl.C2dmHttpPostTest.java

@Test
public void entityContainsDataPairs() throws IOException {
    List<NameValuePair> data = URLEncodedUtils.parse(post.getEntity());
    assertThat(data.contains(new BasicNameValuePair(String.format("data.%s", DATA_KEY), DATA_VALUE)), is(true));
}

From source file:org.whitesource.agent.client.WssServiceClientTest.java

@Test
public void testUpdateRequestSentOk() {
    final Collection<AgentProjectInfo> projects = new ArrayList<AgentProjectInfo>();
    final AgentProjectInfo projectInfo = new AgentProjectInfo();
    projectInfo.setProjectToken("projectToken");
    projectInfo.setCoordinates(new Coordinates("groupId", "artifactId", "version"));
    projectInfo.setParentCoordinates(new Coordinates("groupId", "parent-artifactId", "version"));
    final DependencyInfo dependencyInfo = new DependencyInfo("dep-groupId", "dep-artifactId", "dep-version");
    projectInfo.getDependencies().add(dependencyInfo);
    projects.add(projectInfo);//from  w w  w. j  a va  2  s  .com
    final UpdateInventoryRequest updateInventoryRequest = requestFactory.newUpdateInventoryRequest("orgToken",
            projects);

    HttpRequestHandler handler = new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            List<NameValuePair> nvps = URLEncodedUtils.parse(entity);
            for (NameValuePair nvp : nvps) {
                if (nvp.getName().equals(APIConstants.PARAM_REQUEST_TYPE)) {
                    assertEquals(nvp.getValue(), updateInventoryRequest.type().toString());
                } else if (nvp.getName().equals(APIConstants.PARAM_AGENT)) {
                    assertEquals(nvp.getValue(), updateInventoryRequest.agent());
                } else if (nvp.getName().equals(APIConstants.PARAM_AGENT_VERSION)) {
                    assertEquals(nvp.getValue(), updateInventoryRequest.agentVersion());
                } else if (nvp.getName().equals(APIConstants.PARAM_TOKEN)) {
                    assertEquals(nvp.getValue(), updateInventoryRequest.orgToken());
                } else if (nvp.getName().equals(APIConstants.PARAM_TIME_STAMP)) {
                    assertEquals(nvp.getValue(), Long.toString(updateInventoryRequest.timeStamp()));
                } else if (nvp.getName().equals(APIConstants.PARAM_DIFF)) {
                    Gson gson = new Gson();
                    Type type = new TypeToken<Collection<AgentProjectInfo>>() {
                    }.getType();
                    final Collection<AgentProjectInfo> tmpProjects = gson.fromJson(nvp.getValue(), type);
                    assertEquals(tmpProjects.size(), 1);
                    final AgentProjectInfo info = tmpProjects.iterator().next();
                    assertEquals(info.getProjectToken(), projectInfo.getProjectToken());
                    assertEquals(info.getCoordinates(), projectInfo.getCoordinates());
                    assertEquals(info.getParentCoordinates(), projectInfo.getParentCoordinates());
                    assertEquals(info.getDependencies().size(), 1);
                    assertEquals(info.getDependencies().iterator().next(), dependencyInfo);
                }
            }
        }
    };
    server.register("/agent", handler);
    try {
        client.updateInventory(updateInventoryRequest);
    } catch (WssServiceException e) {
        // suppress exception
    }
}

From source file:com.socialize.test.blackbox.CommentFactoryBlackboxTest.java

@UsesMocks({ SocializeSession.class })
public void testCreateRequest() throws Throwable {

    SocializeSession session = AndroidMock.createMock(SocializeSession.class);
    final String endPoint = "foobar";

    Comment comment0 = new Comment();
    Comment comment1 = new Comment();
    Comment comment2 = new Comment();

    comment0.setEntityKey("http://www.example.com/interesting-story/");
    comment0.setText("this was a great story");

    Entity entity0 = new Entity();
    entity0.setKey("http://www.example.com/another-story/");
    entity0.setName("Another Interesting Story");

    comment1.setEntity(entity0);//  w  w w . j a v a2 s  .c o  m
    comment1.setText("Another comment");

    comment2.setEntityKey("http://www.example.com/interesting-story/");
    comment2.setText("I did not think the story was that great");

    List<Comment> objects = new ArrayList<Comment>();
    objects.add(comment0);
    objects.add(comment1);
    objects.add(comment2);

    HttpUriRequest request = requestFactory.getPostRequest(session, endPoint, objects);

    assertTrue(request instanceof HttpEntityEnclosingRequest);

    HttpEntityEnclosingRequest eReq = (HttpEntityEnclosingRequest) request;

    HttpEntity entity = eReq.getEntity();

    assertNotNull(entity);

    assertTrue(entity instanceof UrlEncodedFormEntity);

    List<NameValuePair> parsed = URLEncodedUtils.parse(entity);

    assertEquals(1, parsed.size());

    NameValuePair nvp = parsed.get(0);

    assertEquals("payload", nvp.getName());

    String strActual = nvp.getValue();
    String strExpected = getSampleJSON(JSON_REQUEST_COMMENT_CREATE);

    JSONArray actual = new JSONArray(strActual);
    JSONArray expected = new JSONArray(strExpected);

    JsonAssert.assertJsonArrayEquals(expected, actual);
}

From source file:org.acoustid.server.util.ParameterMap.java

public static ParameterMap parseRequest(HttpServletRequest request) throws IOException {
    String contentEncoding = request.getHeader("Content-Encoding");
    if (contentEncoding != null) {
        contentEncoding = contentEncoding.toLowerCase();
    }/*from w  w  w.  j  a v  a 2  s  .  co m*/
    String contentType = request.getContentType();
    Map<String, String[]> map;
    if ("gzip".equals(contentEncoding) && "application/x-www-form-urlencoded".equals(contentType)) {
        InputStream inputStream = new GZIPInputStream(request.getInputStream());
        InputStreamEntity entity = new InputStreamEntity(inputStream, -1);
        entity.setContentType(contentType);
        map = new HashMap<String, String[]>();
        for (NameValuePair param : URLEncodedUtils.parse(entity)) {
            String name = param.getName();
            String value = param.getValue();
            String[] values = map.get(name);
            if (values == null) {
                values = new String[] { value };
            } else {
                values = (String[]) ArrayUtils.add(values, value);
            }
            map.put(name, values);
        }
    } else {
        map = request.getParameterMap();
    }
    return new ParameterMap(map);
}

From source file:edu.mit.mobile.android.demomode.Preferences.java

private void fromCfgString(String cfg) {
    final Uri cfgUri = Uri.parse(cfg);
    if ("data".equals(cfgUri.getScheme())) {
        final String[] cfgParts = cfgUri.getEncodedSchemeSpecificPart().split(",", 2);
        if (CFG_MIME_TYPE.equals(cfgParts[0])) {
            final Editor ed = mPrefs.edit();
            final ArrayList<ContentProviderOperation> cpos = new ArrayList<ContentProviderOperation>();

            // first erase everything
            cpos.add(ContentProviderOperation.newDelete(LauncherItem.CONTENT_URI).build());

            try {
                final StringEntity entity = new StringEntity(cfgParts[1]);
                entity.setContentType("application/x-www-form-urlencoded");
                final List<NameValuePair> nvp = URLEncodedUtils.parse(entity);
                for (final NameValuePair pair : nvp) {
                    final String name = pair.getName();
                    Log.d(TAG, "parsed pair: " + pair);
                    if (CFG_K_SECRETKEY.equals(name)) {
                        ed.putString(KEY_PASSWORD, pair.getValue());

                    } else if (CFG_K_APPS.equals(name)) {
                        final String[] app = pair.getValue().split(CFG_PKG_SEP, 2);
                        final ContentProviderOperation cpo = ContentProviderOperation
                                .newInsert(LauncherItem.CONTENT_URI)
                                .withValue(LauncherItem.PACKAGE_NAME, app[0])
                                .withValue(LauncherItem.ACTIVITY_NAME, app[1]).build();
                        cpos.add(cpo);//from  w  ww. j av a  2 s  .  c  o m
                        Log.d(TAG, "adding " + cpo);
                    }
                }

                ed.commit();
                getContentResolver().applyBatch(HomescreenProvider.AUTHORITY, cpos);
            } catch (final UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (final IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (final RemoteException e) {
                // TODO Auto-generated catch block

                e.printStackTrace();
            } catch (final OperationApplicationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            Log.e(TAG, "unknown MIME type for data URI: " + cfgParts[0]);
        }

    } else {
        Log.e(TAG, "not a data URI");
    }
}