Example usage for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity

List of usage examples for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity

Introduction

In this page you can find the example usage for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity.

Prototype

public UrlEncodedFormEntity(final Iterable<? extends NameValuePair> parameters, final Charset charset) 

Source Link

Document

Constructs a new UrlEncodedFormEntity with the list of parameters in the specified encoding.

Usage

From source file:org.ambraproject.action.article.MediaCoverageAction.java

@Override
public String execute() throws Exception {

    String status = ERROR;//from  w ww. j av a  2s . co m

    if (validateInput() == false) {
        addActionError("Invalid values have been submitted.");
        return status;
    }

    HttpClient httpClient = new DefaultHttpClient();

    String linkComment = this.name + ", " + this.email + "\n" + this.comment;

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("doi", this.uri.replaceFirst("info:doi/", "")));
    params.add(new BasicNameValuePair("link", this.link));
    params.add(new BasicNameValuePair("comment", linkComment));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");

    String mediaCurationUrl = configuration.getString("ambra.services.mediaCoverage.url", null);

    if (mediaCurationUrl != null) {
        HttpPost httpPost = new HttpPost(mediaCurationUrl);
        try {
            httpPost.setEntity(entity);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();

            // check for status code
            if (statusCode == HttpStatus.SC_CREATED) {
                status = SUCCESS;
            }

        } catch (Exception e) {
            log.error("Failed to submit the link to media curation app", e);
            addActionError("There was an error while submitting the media coverage link.");
        } finally {
            httpPost.releaseConnection();
        }
    }

    return status;

}

From source file:com.jaeksoft.searchlib.test.legacy.CommonTestCase.java

public HttpPost queryInstance(List<NameValuePair> namedValuePairs, String apiPath, boolean use)
        throws IllegalStateException, IOException {
    HttpPost httpPost = null;//w w w. ja  v a2s.c o  m
    httpPost = new HttpPost(SERVER_URL + "/" + apiPath);
    if (use)
        namedValuePairs.add(new BasicNameValuePair("use", INDEX_NAME));
    namedValuePairs.add(new BasicNameValuePair("login", USER_NAME));
    namedValuePairs.add(new BasicNameValuePair("key", API_KEY));
    httpPost.setEntity(new UrlEncodedFormEntity(namedValuePairs, "UTF-8"));
    return httpPost;
}

From source file:jp.tonyu.soytext2.file.Comm.java

public Scriptable exec(String rootPath, String relPath, Scriptable sparams, Object responseType)
        throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(rootPath + relPath);
    final List<NameValuePair> params = new Vector<NameValuePair>();
    Scriptables.each(sparams, new StringPropAction() {

        @Override//from  w  w  w.j  a va 2  s .com
        public void run(String key, Object value) {
            if (value instanceof String) {
                String s = (String) value;
                params.add(new BasicNameValuePair(key, s));
            }
        }
    });
    httppost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));

    HttpResponse response = httpclient.execute(httppost);
    return response2Scriptable(response, responseType);
}

From source file:outfox.dict.contest.test.InitSingerData.java

@ResponseBody
@RequestMapping(value = "/initData")
public String initData() {
    SingerEntity singerEntity = new SingerEntity();

    // 10000??/*from w  ww.  j ava  2  s  .c om*/
    for (int i = 1; i <= 10; i++) {
        // ????
        singerEntity.setUserId(String.valueOf(i));
        singerEntity.setName("" + i);
        singerEntity.setSchool(getRandomSchool());
        singerEntity.setAreaName(getRandomCity());
        singerEntity.setPhotoUrl("http://p1.music.126.net/aHW-oDNmj4FcuB34vmg4Ng==/2544269906854087.jpg");
        singerEntity.setAudioUrl("http://m2.music.126.net/S7r4Uu8mPCwNhvHcfVbtEA==/2029698464885626.mp3");
        singerEntity.setAge(18);
        singerEntity.setSex(false);
        singerEntity.setMusicName("" + i);
        singerEntity.setPhone("121221" + i);

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        singerEntity.setSingupTime(timestamp);

        // 1: ?
        contestDAO.signup(singerEntity);

        // 2: ??
        String content = "{\"id\": " + singerEntity.getId() + ", \"name\": \"" + singerEntity.getName()
                + "\", \"school\": \"" + singerEntity.getSchool() + "\", \"areaName\": \""
                + singerEntity.getAreaName() + "\", \"audioUrl\": \"" + singerEntity.getAudioUrl() + "\"}";
        HttpResponse response = null;
        try {
            List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
            paramsList.add(new BasicNameValuePair("voteId", ContestConsts.VOTE_ID));
            paramsList.add(new BasicNameValuePair("content", content));
            paramsList.add(new BasicNameValuePair("picture", singerEntity.getPhotoUrl()));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramsList, "UTF-8");
            response = HttpToolKit.getInstance().doPost(ContestConsts.ADD_VOTE_OPTION_INTERFACE, entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HttpToolKit.closeQuiet(response);
        }
        System.out.println("*********" + i + "???*********");
    }
    return Result.SUCCESS.json(null, null);
}

From source file:ch.ralscha.extdirectspring_itest.UserInitBinderServiceTest.java

@Test
public void testPostWithoutDate() throws IOException {
    Locale.setDefault(Locale.ENGLISH);
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("extTID", "1"));
    formparams.add(new BasicNameValuePair("extAction", "userServiceInitBinderService"));
    formparams.add(new BasicNameValuePair("extMethod", "updateUser"));
    formparams.add(new BasicNameValuePair("extType", "rpc"));
    formparams.add(new BasicNameValuePair("extUpload", "false"));
    formparams.add(new BasicNameValuePair("name", "Garner"));
    formparams.add(new BasicNameValuePair("firstName", "Joe"));
    formparams.add(new BasicNameValuePair("email", "test@test.com"));
    formparams.add(new BasicNameValuePair("age", "28"));
    formparams.add(new BasicNameValuePair("flag", "false"));
    formparams.add(new BasicNameValuePair("dateOfBirth", ""));
    UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

    this.post.setEntity(postEntity);

    CloseableHttpResponse response = this.client.execute(this.post);
    try {/*from  ww w .  j  ava 2  s .  c  om*/
        HttpEntity entity = response.getEntity();
        assertThat(entity).isNotNull();
        String responseString = EntityUtils.toString(entity);

        Map<String, Object> rootAsMap = this.mapper.readValue(responseString, Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("method")).isEqualTo("updateUser");
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("userServiceInitBinderService");
        assertThat(rootAsMap.get("tid")).isEqualTo(1);

        Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
        assertThat(result).hasSize(6);
        assertThat(result.get("name")).isEqualTo("Garner");
        assertThat(result.get("firstName")).isEqualTo("Joe");
        assertThat(result.get("age")).isEqualTo(28);
        assertThat(result.get("email")).isEqualTo("test@test.com");
        assertThat(result.get("flag")).isEqualTo(Boolean.FALSE);
        assertThat(result.get("dateOfBirth")).isNull();
        assertThat(result.get("success")).isEqualTo(Boolean.TRUE);
    } finally {
        IOUtils.closeQuietly(response);
    }
}

From source file:HttpsRequestDemo.java

private String sentHttpPostRequest(String requestMsg) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();

    // SSLSocketFactory
    registerSSLSocketFactory(httpclient);

    // /*from   w w w  .  j a  v a2 s  .co  m*/
    int timeout = 60000;
    HttpConnectionParams.setSoTimeout(httpclient.getParams(), timeout);

    // post
    HttpPost httppost = new HttpPost(targetURL);

    // 
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    // 
    params.add(new BasicNameValuePair("messageRouter", messageRouter));
    // 
    params.add(new BasicNameValuePair("tradingPartner", partnerCode));
    // 
    params.add(new BasicNameValuePair("documentProtocol", documentProtocol));
    // xml
    params.add(new BasicNameValuePair("requestMessage", requestMsg));

    // UTF-8
    HttpEntity request = new UrlEncodedFormEntity(params, "UTF-8");
    httppost.setEntity(request);

    // xmlxml
    HttpResponse httpResponse = httpclient.execute(httppost);
    HttpEntity entity = httpResponse.getEntity();
    String result = null;
    if (entity != null) {
        result = EntityUtils.toString(entity);
    }

    return result;
}

From source file:org.opencastproject.remotetest.server.WorkflowRestEndpointTest.java

@Test
public void testStartAndRetrieveWorkflowInstance() throws Exception {
    // Start a workflow instance via the rest endpoint
    HttpPost postStart = new HttpPost(BASE_URL + "/workflow/start");
    List<NameValuePair> formParams = new ArrayList<NameValuePair>();

    formParams.add(new BasicNameValuePair("definition", getSampleWorkflowDefinition()));
    formParams.add(new BasicNameValuePair("mediapackage", getSampleMediaPackage()));
    formParams.add(new BasicNameValuePair("properties", "this=that"));
    postStart.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));

    // Grab the new workflow instance from the response
    HttpResponse r = client.execute(postStart);
    Assert.assertEquals(200, r.getStatusLine().getStatusCode());
    String postResponse = EntityUtils.toString(r.getEntity());
    String id = getWorkflowInstanceId(postResponse);

    // Ensure we can retrieve the workflow instance from the rest endpoint
    HttpGet getWorkflowMethod = new HttpGet(BASE_URL + "/workflow/instance/" + id + ".xml");
    String getResponse = EntityUtils.toString(client.execute(getWorkflowMethod).getEntity());
    Assert.assertEquals(id, getWorkflowInstanceId(getResponse));

    // Make sure we can retrieve it via json, too
    HttpGet getWorkflowJson = new HttpGet(BASE_URL + "/workflow/instance/" + id + ".json");
    String jsonResponse = EntityUtils.toString(client.execute(getWorkflowJson).getEntity());
    JSONObject json = (JSONObject) JSONValue.parse(jsonResponse);
    if (json == null)
        Assert.fail("JSON response should not be null, but is " + jsonResponse);
    JSONObject workflowAsJson = (JSONObject) json.get("workflow");
    Assert.assertEquals(id, workflowAsJson.get("id"));

    // Make sure we can retrieve it as part of a set of workflows as json
    HttpGet getWorkflowsJson = new HttpGet(BASE_URL + "/workflow/instances.json");
    String workflowsResponse = EntityUtils.toString(client.execute(getWorkflowsJson).getEntity());
    JSONObject workflowsJson = (JSONObject) JSONValue.parse(workflowsResponse);
    if (workflowsJson == null)
        Assert.fail("JSON response should not be null, but is " + jsonResponse);
    JSONObject workflows = (JSONObject) workflowsJson.get("workflows");
    Assert.assertTrue(Integer.parseInt((String) workflows.get("totalCount")) > 0);

    // Ensure that the workflow finishes successfully
    int attempts = 0;
    while (true) {
        if (++attempts == 20)
            Assert.fail("workflow rest endpoint test has hung");
        getWorkflowMethod = new HttpGet(BASE_URL + "/workflow/instance/" + id + ".xml");
        getResponse = EntityUtils.toString(client.execute(getWorkflowMethod).getEntity());
        String state = getWorkflowInstanceStatus(getResponse);
        if ("FAILED".equals(state))
            Assert.fail("workflow instance " + id + " failed");
        if ("SUCCEEDED".equals(state))
            break;
        System.out.println("workflow " + id + " is " + state);
        Thread.sleep(5000);//from w ww  .  jav  a2s  .  c o  m
    }
}

From source file:cn.sharesdk.analysis.net.NetworkHelper.java

public static PostResult post(String url, String data, String appkey) {

    //Ln.i(" post msg url ==>>", url);
    //Ln.i(" post msg appkey ==>>", appkey);

    PostResult postResult = new PostResult();
    if (TextUtils.isEmpty(appkey)) {
        postResult.setSuccess(false);/*from ww w  .  j av  a  2s. c  o  m*/
        postResult.setResponseMsg("appkey is null");
        return postResult;
    }
    HttpPost httppost = new HttpPost(url);
    HttpClient httpclient = new DefaultHttpClient();
    try {
        Ln.i("postdata before base64gizp", "client_data:" + data);

        ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("appkey", appkey));
        if (!TextUtils.isEmpty(data)) {
            data = Base64Gzip(data);
            pairs.add(new BasicNameValuePair("m", data));
        }
        HttpEntity entity = new UrlEncodedFormEntity(pairs, HTTP.UTF_8);
        httppost.addHeader("charset", HTTP.UTF_8);
        httppost.setHeader("Accept", "application/json,text/x-json,application/jsonrequest,text/json");
        httppost.setEntity(entity);

        HttpResponse response = httpclient.execute(httppost);
        int status = response.getStatusLine().getStatusCode();

        String resString = EntityUtils.toString(response.getEntity());
        postResult = parse(status, resString);

    } catch (Exception e) {
        Ln.e("NetworkHelper", "=== post Ln ===", e);
    }
    return postResult;
}

From source file:org.lol.reddit.cache.CacheDownload.java

public CacheDownload(final CacheRequest initiator, final CacheManager manager,
        final PrioritisedDownloadQueue queue) {

    this.mInitiator = initiator;

    this.manager = manager;
    this.mQueue = queue;

    if (!initiator.setDownload(this)) {
        cancel();//from   ww  w  . j  a v a2s  . com
    }

    if (initiator.requestSession != null) {
        session = initiator.requestSession;
    } else {
        session = UUID.randomUUID();
    }

    if (mInitiator.postFields != null) {
        final HttpPost httpPost = new HttpPost(mInitiator.url);
        mHttpRequest = httpPost;
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(mInitiator.postFields, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            BugReportActivity.handleGlobalError(initiator.context, e);
        }

    } else {
        mHttpRequest = new HttpGet(mInitiator.url);
    }
}

From source file:de.unistuttgart.ipvs.pmp.resourcegroups.vHikeWS.resource.JSonRequestProvider.java

/**
 * Sending a request to the WEBSERVICE_URL defined in {@link Constants}
 * //from w  ww .j  a v  a  2  s  .c o m
 * @param listToParse
 *            contains all the parameters, which have to be parsed
 * @param url
 * @param debug
 *            mode true or false
 * @return JsonObject
 * @throws IOException
 * @throws ClientProtocolException
 */
public static JsonObject doRequest(List<ParamObject> listToParse, String url)
        throws ClientProtocolException, IOException {

    // GET REQUESTS
    StringBuffer buf = new StringBuffer();
    buf.append(url);
    buf.append("?");

    for (ParamObject object : listToParse) {

        if (!(object.isPost())) {
            buf.append(object.getKey() + "=" + object.getValue());
            buf.append("&");
            // getParam = getParam + object.getKey() + "=" +
            // object.getValue();
            // getParam = getParam + "&";
        }
    }
    String getParam = buf.toString();
    // Cut the last '&' out
    getParam = getParam.substring(0, getParam.length() - 1);

    Log.d(TAG, "Param: " + getParam);

    // Create a new HttpClient and Post Header

    HttpPost httppost = new HttpPost(Constants.WEBSERVICE_URL + getParam);

    List<NameValuePair> namelist = new ArrayList<NameValuePair>(listToParse.size());

    // Iterate over objects, which have to be post to the web service
    // POST REQUESTS
    for (ParamObject object : listToParse) {
        if ((object.isPost())) {
            namelist.add(new BasicNameValuePair(object.getKey(), object.getValue()));
            // TODO: Remove this line
            Log.d(TAG, "POST: " + object.getKey() + " - " + object.getValue());
        }
    }

    httppost.setEntity(new UrlEncodedFormEntity(namelist, "UTF-8"));

    // Execute HTTP Post Request
    HttpResponse response;
    JsonObject jsonObject = null;
    response = httpclient.execute(httppost);
    // for JSON:
    if (response != null) {
        InputStream is = response.getEntity().getContent();
        BufferedReader r = new BufferedReader(new InputStreamReader(is));
        try {
            StringBuffer sb = new StringBuffer();
            String s = null;
            while ((s = r.readLine()) != null) {
                sb.append(s).append(System.getProperty("line.separator"));
            }
            s = sb.toString();

            jsonObject = (new JsonParser()).parse(s).getAsJsonObject();
            Log.d(TAG, "======DEBUG=====");
            Log.d(TAG, s);
            Log.d(TAG, "======DEBUG=====");
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
    } else {
        Log.d(TAG, "No Response");
    }
    return jsonObject;
}