Example usage for org.apache.http.client.methods HttpPost HttpPost

List of usage examples for org.apache.http.client.methods HttpPost HttpPost

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPost HttpPost.

Prototype

public HttpPost(final String uri) 

Source Link

Usage

From source file:com.buddycloud.friendfinder.HttpUtils.java

public static void post(String URL, Map<String, String> params) throws Exception {
    HttpClient client = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(URL);
    HttpParams httpParams = new BasicHttpParams();
    for (Entry<String, String> entryParam : params.entrySet()) {
        httpParams.setParameter(entryParam.getKey(), entryParam.getValue());
    }/*w  w  w .j  a  v  a2  s .  co m*/
    httpPost.setParams(httpParams);
    client.execute(httpPost);
}

From source file:com.tedx.webservices.WebServices.java

public static JSONArray SendHttpPostArray(String URL, JSONObject jsonObjSend) {
    try {// ww  w  . j av  a  2s . c om
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        //httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();

            // Transform the String into a JSONObject
            JSONArray jsonObjRecv = new JSONArray(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<jsonobject>\n" + jsonObjRecv.toString() + "\n</jsonobject>");

            return jsonObjRecv;
        }
    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}

From source file:org.megam.deccanplato.http.TransportMachinery.java

public static TransportResponse post(TransportTools nuts) throws ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(nuts.urlString());
    System.out.println("NUTS" + nuts.toString());
    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {
            //this if condition is set for twilio Rest API to add credentials to DefaultHTTPClient, conditions met twilio work.
            if (headerEntry.getKey().equalsIgnoreCase("provider")
                    & headerEntry.getValue().equalsIgnoreCase(nuts.headers().get("provider"))) {
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(
                                nuts.headers().get("account_sid"), nuts.headers().get("oauth_token")));
            }//from www . ja  va2  s. c  o  m
            //this else part statements for other providers
            else {
                httppost.addHeader(headerEntry.getKey(), headerEntry.getValue());
            }
        }
    }
    if (nuts.fileEntity() != null) {
        httppost.setEntity(nuts.fileEntity());
    }
    if (nuts.pairs() != null && (nuts.contentType() == null)) {
        httppost.setEntity(new UrlEncodedFormEntity(nuts.pairs()));
    }

    if (nuts.contentType() != null) {
        httppost.setEntity(new StringEntity(nuts.contentString(), nuts.contentType()));
    }
    TransportResponse transportResp = null;
    System.out.println(httppost.toString());
    try {
        HttpResponse httpResp = httpclient.execute(httppost);
        transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(),
                httpResp.getLocale());
    } finally {
        httppost.releaseConnection();
    }
    return transportResp;

}

From source file:com.wbtech.dao.NetworkUitlity.java

public static MyMessage post(String url, String data) {
    // TODO Auto-generated method stub
    String returnContent = "";
    MyMessage message = new MyMessage();
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    try {//from   w  w w.  j  a  va  2  s .c  o m
        StringEntity se = new StringEntity("content=" + data, HTTP.UTF_8);
        Log.d("postdata", "content=" + data);
        se.setContentType("application/x-www-form-urlencoded");
        httppost.setEntity(se);
        HttpResponse response = httpclient.execute(httppost);
        int status = response.getStatusLine().getStatusCode();

        String returnXML = EntityUtils.toString(response.getEntity());
        returnContent = URLDecoder.decode(returnXML);
        switch (status) {
        case 200:
            message.setFlag(true);
            message.setMsg(returnContent);
            break;

        default:
            Log.e("error", status + returnContent);
            message.setFlag(false);
            message.setMsg(returnContent);
            break;
        }
    } catch (Exception e) {
        JSONObject jsonObject = new JSONObject();

        if (e.getMessage().equalsIgnoreCase("no route to host")) {
            try {
                jsonObject.put("err", "??,???");
                returnContent = jsonObject.toString();
                message.setFlag(false);
                message.setMsg(returnContent);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }

        else if (e.getMessage().equalsIgnoreCase("network unreachable")
                || e.getMessage().equalsIgnoreCase("www.cobub.com")) {
            try {
                jsonObject.put("err", "");
                returnContent = jsonObject.toString();
                message.setFlag(false);
                message.setMsg(returnContent);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }

        else {
            try {
                jsonObject.put("err", "");
                returnContent = jsonObject.toString();
                message.setFlag(false);
                message.setMsg(returnContent);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }

    }
    return message;
}

From source file:middleware.HTTPRequest.java

public static void doPostVuelo(String jsonRequest) throws UnsupportedEncodingException, IOException {
    String url = "http://localhost:8084/MVIv2/webapi/vuelos";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(url);
    StringEntity input = new StringEntity(jsonRequest);
    input.setContentType("application/json");
    postRequest.setEntity(input);// ww w  .ja va 2  s.  co m

    HttpResponse response = httpClient.execute(postRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("ERROR AL INSERTAR DEL TIPO: " + response.getStatusLine().getStatusCode());
    }

    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();

}

From source file:org.wso2.dss.integration.test.odata.ODataTestUtils.java

public static Object[] sendPOST(String endpoint, String content, Map<String, String> headers)
        throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(endpoint);
    for (String headerType : headers.keySet()) {
        httpPost.setHeader(headerType, headers.get(headerType));
    }/*from w  w w  .j av  a2s  .c om*/
    if (null != content) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        if (headers.get("Content-Type") == null) {
            httpPost.setHeader("Content-Type", "application/json");
        }
        httpPost.setEntity(httpEntity);
    }
    HttpResponse httpResponse = httpClient.execute(httpPost);
    if (httpResponse.getEntity() != null) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();
        return new Object[] { httpResponse.getStatusLine().getStatusCode(), response.toString() };
    } else {
        return new Object[] { httpResponse.getStatusLine().getStatusCode() };
    }
}

From source file:markson.visuals.sitapp.JSONfunctions.java

public static JSONObject getJSONfromURL(String url) {

    //initialize/*from  ww  w.j av a  2s. c  o  m*/
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    //http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    //convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    //try parse the string to a JSON object
    try {
        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}

From source file:org.opencastproject.remotetest.server.resource.FilesResources.java

public static HttpResponse postFile(TrustedHttpClient client, String mediaPackageID,
        String mediaPackageElementID, String media) throws Exception {
    HttpPost post = new HttpPost(
            getServiceUrl() + "mediapackage/" + mediaPackageElementID + "/" + mediaPackageElementID);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new FileBody(new File(media)));
    post.setEntity(entity);/*from w w w  .  j  a va  2 s  . co m*/
    return client.execute(post);
}

From source file:net.modelbased.proasense.storage.registry.RegisterSensorSSN.java

public static String postSensor(Sensor sensor) throws RequestErrorException {
    String content = JsonPrinter.sensorToJson(sensor);
    URI target;/*from  w  w  w.  j av  a2 s.  c  o  m*/
    try {
        target = new URI(sensor.getUri().toString() + SENSOR_PATH);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        throw new RequestErrorException(e1.getMessage());
    }
    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost(target);
    request.setHeader("Content-type", "application/json");
    String response = null;
    try {
        StringEntity seContent = new StringEntity(content);
        seContent.setContentType("text/json");
        request.setEntity(seContent);
        response = resolveResponse(client.execute(request));
    } catch (Exception e) {
        throw new RequestErrorException(e.getMessage());
    }
    return response;
}