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) 

Source Link

Document

Constructs a new UrlEncodedFormEntity with the list of parameters with the default encoding of HTTP#DEFAULT_CONTENT_CHARSET

Usage

From source file:org.fcrepo.integration.api.FedoraFieldSearchIT.java

@Test
public void testSearchSubmitPaging() throws Exception {
    final HttpPost method = new HttpPost(serverAddress + "search");
    final List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();

    list.add(new BasicNameValuePair("terms", ""));
    list.add(new BasicNameValuePair("offset", "1"));
    list.add(new BasicNameValuePair("maxResults", "1"));
    final UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
    method.setEntity(formEntity);//from ww w.  ja  va2s . c  om
    assertEquals(200, getStatus(method));

}

From source file:org.n52.sir.IT.ValidatorBindingIT.java

@Test
public void readValidSensorMLAndValidate() throws IOException {
    File f = new File(ClassLoader.getSystemResource("AirBase-test.xml").getFile());
    BufferedReader reader = new BufferedReader(new FileReader(f));
    String s = null;//from  w  ww  . jav a  2  s  .co m
    StringBuilder builder = new StringBuilder();
    while ((s = reader.readLine()) != null)
        builder.append(s);
    String sensorML = builder.toString();
    HttpPost post = new HttpPost("http://localhost:8080/OpenSensorSearch/api/check/sensorML");
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("sensor", sensorML));
    pairs.add(new BasicNameValuePair("format", "json"));
    post.setEntity(new UrlEncodedFormEntity(pairs));

    HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);
    StringBuilder result = new StringBuilder();
    reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    while ((s = reader.readLine()) != null)
        result.append(s);
    StatusResponse sr = new Gson().fromJson(result.toString(), StatusResponse.class);

    assertEquals("valid", sr.status);
}

From source file:com.rumblefish.friendlymusic.api.WebRequest.java

public static String webRequest(URLRequest request) {
    HttpPost httpPost = null;//from www. jav  a2 s  . c  om
    HttpGet httpGet = null;
    if (request.m_nameValuePairs != null) {
        httpPost = new HttpPost(request.m_serverURL);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(request.m_nameValuePairs));
        } catch (Exception e) {
            return null;
        }
    } else {
        httpGet = new HttpGet(request.m_serverURL);
        Log.v(LOGTAG, request.m_serverURL);
    }

    HttpClient client = getNewHttpClient(request.m_timelimit);

    StringBuilder builder = new StringBuilder();

    try {
        HttpResponse response;
        if (request.m_nameValuePairs != null)
            response = client.execute(httpPost);
        else
            response = client.execute(httpGet);

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            try {
                content.close();
            } catch (IOException e) {

            }
        } else {
            Log.e("WebRequest", "Failed to download file");
            return null;
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.getConnectionManager().closeExpiredConnections();
        client.getConnectionManager().closeIdleConnections(0, TimeUnit.NANOSECONDS);
    }

    String resultString = builder.toString();
    try {
        if (resultString == null || resultString.length() == 0) {
            return null;
        }
        return resultString;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.kei.android.phone.mangastore.http.HttpTaskFetch.java

@Override
protected JSONArray doInBackground(final String... params) {
    JSONArray result = null;//from  w  ww  .j a  v a 2s. c  o  m
    BufferedReader reader = null;
    try {
        final HttpClient client = new DefaultHttpClient();
        final HttpPost httpPost = new HttpPost(params[0]);
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("android_name", params[1]));
        nameValuePairs.add(new BasicNameValuePair("android_password", params[2]));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        final HttpResponse response = client.execute(httpPost);
        final StatusLine statusLine = response.getStatusLine();
        final int code = statusLine.getStatusCode();
        if (code == 200) {
            final StringBuilder sb = new StringBuilder();
            final HttpEntity entity = response.getEntity();
            final InputStream content = entity.getContent();
            reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null)
                sb.append(line);
            result = new JSONArray(sb.toString());
        } else {
            throw new IOException(
                    "The server has responded an error " + code + " (" + statusLine.getReasonPhrase() + ")");
        }
    } catch (final Exception e) {
        t.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                t.onTaskError(e);
            }
        });
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
            }
        }
    }
    return result;
}

From source file:srdes.menupp.EntreeDbAdapter.java

/**
 * @brief   Create a new review using the title and body provided. If the review is
 *          successfully created return the new rowId for that review, otherwise return
 *          a -1 to indicate failure.//from   www  . ja  v  a  2  s . co m
 * 
 * @param    title the title of the note
 * 
 * @param    body the body of the note
 * 
 * @param    entree the name of the entree the review is for
 * 
 * @param    rating the rating given to the entree in the review
 * 
 * @throws    JSONException if cannot get rowID
 * 
 * @return    rowId or -1 if failed
 */
public static Long createReview(String title, String body, String entree, float rating) throws JSONException {

    //add column information to pass to database
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair(KEY_TITLE, title));
    nameValuePairs.add(new BasicNameValuePair(KEY_BODY, body));
    nameValuePairs.add(new BasicNameValuePair(KEY_ENTREE, entree));
    nameValuePairs.add(new BasicNameValuePair(KEY_RATING, new Float(rating).toString()));

    //http post
    JSONObject response = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(INSERT_REVIEW_SCRIPT);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httppost, responseHandler);
        response = new JSONObject(responseBody);

    } catch (ClientProtocolException e) {
        DebugLog.LOGD("Protocol error in http connection " + e.toString());
    } catch (UnsupportedEncodingException e) {
        DebugLog.LOGD("Encoding error in http connection " + e.toString());
    } catch (IOException e) {
        DebugLog.LOGD("IO error in http connection " + e.toString());
    }
    //rowID encoded in response
    return (Long) response.get(KEY_ROWID);
}

From source file:org.opencastproject.textanalyzer.remote.TextAnalysisRemoteImpl.java

/**
 * {@inheritDoc}/*w w  w . j  av a2  s .  c  o m*/
 * 
 * @see org.opencastproject.textanalyzer.api.TextAnalyzerService#extract(org.opencastproject.mediapackage.MediaPackageElement)
 */
@Override
public Job extract(final Attachment image) throws TextAnalyzerException {
    HttpPost post = new HttpPost();
    try {
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("image", MediaPackageElementParser.getAsXml(image)));
        post.setEntity(new UrlEncodedFormEntity(params));
    } catch (Exception e) {
        throw new TextAnalyzerException(e);
    }
    HttpResponse response = null;
    try {
        response = getResponse(post);
        if (response != null) {
            try {
                Job receipt = JobParser.parseJob(response.getEntity().getContent());
                logger.info("Analyzing {} on a remote analysis server", image);
                return receipt;
            } catch (Exception e) {
                throw new TextAnalyzerException(
                        "Unable to analyze element '" + image + "' using a remote analysis service", e);
            }
        }
    } finally {
        closeConnection(response);
    }
    throw new TextAnalyzerException(
            "Unable to analyze element '" + image + "' using a remote analysis service");
}

From source file:com.dev.pygmy.game.GameReportTask.java

@Override
protected String doInBackground(String... params) {

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(REPORT_URL);
    ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

    param.add(new BasicNameValuePair("report", mReasons.get(0)));
    param.add(new BasicNameValuePair("name", params[0]));

    InputStream is = null;//  w ww  . jav  a 2  s  . c  om
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(param));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (Exception e) {
        PygmyApp.logE("Error in HTTP connection: " + e.getMessage());
    }

    String result = null;
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        PygmyApp.logE("Error converting result: " + e.getMessage());
    }

    return result;
}

From source file:org.wso2.security.tools.product.manager.handler.HttpRequestHandler.java

/**
 * Send HTTP POST request//ww  w.  j a  v  a  2 s.  c  om
 *
 * @param requestURI Requested URI
 * @return HTTPResponse after executing the command
 */
public static HttpResponse sendPostRequest(String requestURI, ArrayList<NameValuePair> parameters) {
    try {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        HttpClient httpClient = clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
                .build();
        HttpPost httpPostRequest = new HttpPost(requestURI);

        for (NameValuePair parameter : parameters) {
            urlParameters.add(new BasicNameValuePair(parameter.getName(), parameter.getValue()));
        }

        httpPostRequest.setEntity(new UrlEncodedFormEntity(urlParameters));
        return httpClient.execute(httpPostRequest);
    } catch (IOException e) {
        LOGGER.error("Error occurred while sending POST request to " + requestURI, e);
    }
    return null;
}

From source file:ca.ualberta.cs.c301f12t01.serverStorage.Server.java

/**
 * //  www .  j a v  a2 s .c  om
 * @param nvp
 *          NameValuePair to post to the server
 * @return
 *          The json formatted string we got back
 */
public String post(List<BasicNameValuePair> nvp) {
    String jsonStringVersion = null;
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpGet = new HttpPost(serverName);
    try {
        httpGet.setEntity(new UrlEncodedFormEntity(nvp));
        HttpResponse response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //System.out.println(response.getStatusLine());
            InputStream is = entity.getContent();
            jsonStringVersion = ServerUtils.convertStreamToString(is);
        }

        return jsonStringVersion;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null; //hopefully we never get here
}

From source file:com.zhuc.nupay.mcm.app.jbei.HttpApi.java

public String post(String url, List<NameValuePair> params) throws HttpApiException {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(url);
    //        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    //        nvps.add(new BasicNameValuePair("username", "admin"));
    //        nvps.add(new BasicNameValuePair("password", "admin"));
    //        // post?

    CloseableHttpResponse response = null;
    try {/*  w  w w . j av  a  2  s . c om*/
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // ??
            ContentType contentType = ContentType.getOrDefault(entity);
            Charset charset = contentType.getCharset();
            InputStream is = entity.getContent();
            // inputstreamreader???
            BufferedReader br = new BufferedReader(new InputStreamReader(is, charset));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }

            is.close();
            //System.out.println(":->"+sb.toString());

            return sb.toString();
        } else {
            throw new HttpApiException("Empty Response from server");
        }

    } catch (IOException ex) {
        Logger.getLogger(HttpApi.class.getName()).log(Level.SEVERE, null, ex);

        throw new HttpApiException("Network Error", ex);

    } finally {
        try {
            if (response != null)
                response.close();
        } catch (IOException ex) {
            Logger.getLogger(HttpApi.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}