List of usage examples for org.apache.http.entity StringEntity StringEntity
public StringEntity(String str, Charset charset)
From source file:TTrestclient.TeachTimeRESTclient.java
/** * @param args the command line arguments *///w w w .java2 s .c o m public static void main(String[] args) { TeachTimeRESTclient instance = new TeachTimeRESTclient(); //1 -- Lista entries (JSON) /*System.out.println("1 -- Utente (JSON)"); //creiamo la richiesta (GET) HttpGet get_request = new HttpGet(baseURI + "/users/1"); get_request.setHeader("Accept", "application/json"); instance.execute_and_dump(get_request); System.out.println(); //6 -- Creazione System.out.println("6 -- Creazione entry utente"); HttpPost post_request = new HttpPost(baseURI + "/users"); //per una richiesta POST, prepariamo anche il payload specificandone il tipo HttpEntity payload = new StringEntity(dummy_json_entry, ContentType.APPLICATION_JSON); //e lo inseriamo nella richiesta post_request.setEntity(payload); instance.execute_and_dump(post_request); System.out.println();*/ HttpPost post = new HttpPost(baseURI + "/subjects/3"); HttpEntity payload = new StringEntity("{\"nome\":\"diocane\",\"materia_key\":3}", ContentType.APPLICATION_JSON); post.setEntity(payload); instance.execute_and_dump(post); }
From source file:io.aos.protocol.http.httpcommon.ElementalHttpPost.java
public static void main(String... args) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "Test/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("localhost", 8080); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {//from w w w . j av a2s .com HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"), new ByteArrayEntity("This is the second test request".getBytes("UTF-8")), new InputStreamEntity(new ByteArrayInputStream( "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) }; for (int i = 0; i < requestBodies.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/servlets-examples/servlet/RequestInfoExample"); request.setEntity(requestBodies[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
From source file:com.renren.ntc.sg.util.wxpay.https.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream( new File("/Users/allenz/Downloads/wx_cert/apiclient_cert.p12")); try {//www .java 2s .c om keyStore.load(instream, Constants.mch_id.toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, Constants.mch_id.toCharArray()) .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"); System.out.println("executing request" + post.getRequestLine()); String openid = "oQfDLjmZD7Lgynv6vuoBlWXUY_ic"; String nonce_str = Sha1Util.getNonceStr(); String orderId = SUtils.getOrderId(); String re_user_name = "?"; String amount = "1"; String desc = ""; String spbill_create_ip = "123.56.102.224"; String txt = TXT.replace("{mch_appid}", Constants.mch_appid); txt = txt.replace("{mchid}", Constants.mch_id); txt = txt.replace("{openid}", openid); txt = txt.replace("{nonce_str}", nonce_str); txt = txt.replace("{partner_trade_no}", orderId); txt = txt.replace("{check_name}", "FORCE_CHECK"); txt = txt.replace("{re_user_name}", re_user_name); txt = txt.replace("{amount}", amount); txt = txt.replace("{desc}", desc); txt = txt.replace("{spbill_create_ip}", spbill_create_ip); SortedMap<String, String> map = new TreeMap<String, String>(); map.put("mch_appid", Constants.mch_appid); map.put("mchid", Constants.mch_id); map.put("openid", openid); map.put("nonce_str", nonce_str); map.put("partner_trade_no", orderId); //FORCE_CHECK| OPTION_CHECK | NO_CHECK map.put("check_name", "OPTION_CHECK"); map.put("re_user_name", re_user_name); map.put("amount", amount); map.put("desc", desc); map.put("spbill_create_ip", spbill_create_ip); String sign = SUtils.createSign(map).toUpperCase(); txt = txt.replace("{sign}", sign); post.setEntity(new StringEntity(txt, "utf-8")); CloseableHttpResponse response = httpclient.execute(post); try { HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String text; StringBuffer sb = new StringBuffer(); while ((text = bufferedReader.readLine()) != null) { sb.append(text); } String resp = sb.toString(); LoggerUtils.getInstance().log(String.format("req %s rec %s", txt, resp)); if (isOk(resp)) { String payment_no = getValue(resp, "payment_no"); LoggerUtils.getInstance() .log(String.format("order %s pay OK payment_no %s", orderId, payment_no)); } } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:com.cloudhopper.httpclient.util.HttpPostMain.java
static public void main(String[] args) throws Exception { ///*from w ww .j av a 2s. c om*/ // target urls // String strURL = "http://209.226.31.233:9009/SendSmsService/b98183b99a1f473839ce569c78b84dbd"; // Username: Twitter // Password: Twitter123 TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { // allow all } public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { // allow all } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { easyTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", sf, 443); //SchemeRegistry sr = new SchemeRegistry(); //sr.register(http); //sr.register(https); // create and initialize scheme registry //SchemeRegistry schemeRegistry = new SchemeRegistry(); //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // create an HttpClient with the ThreadSafeClientConnManager. // This connection manager must be used if more than one thread will // be using the HttpClient. //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry); //cm.setMaxTotalConnections(1); DefaultHttpClient client = new DefaultHttpClient(); client.getConnectionManager().getSchemeRegistry().register(https); // for (int i = 0; i < 1; i++) { // // create a new ticket id // //String ticketId = TicketUtil.generate(1, System.currentTimeMillis()); /** StringBuilder string0 = new StringBuilder(200) .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n") .append(" <S:Header>\n") .append(" <ns3:TransactionID xmlns:ns4=\"http://vmp.vzw.com/schema\"\n") .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\">" + ticketId + "</ns3:TransactionID>\n") .append(" </S:Header>\n") .append(" <S:Body>\n") .append(" <ns2:OptinReq xmlns:ns4=\"http://schemas.xmlsoap.org/soap/envelope/\"\n") .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\"\n") .append("xmlns:ns2=\"http://vmp.vzw.com/schema\">\n") .append(" <ns2:VASPID>twitter</ns2:VASPID>\n") .append(" <ns2:VASID>tm33t!</ns2:VASID>\n") .append(" <ns2:ShortCode>800080008001</ns2:ShortCode>\n") .append(" <ns2:Number>9257089093</ns2:Number>\n") .append(" <ns2:Source>provider</ns2:Source>\n") .append(" <ns2:Message/>\n") .append(" </ns2:OptinReq>\n") .append(" </S:Body>\n") .append("</S:Envelope>"); */ // simple send sms StringBuilder string1 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:loc=\"http://www.csapi.org/schema/parlayx/sms/send/v2_3/local\">\n") .append(" <soapenv:Header/>\n").append(" <soapenv:Body>\n").append(" <loc:sendSms>\n") .append(" <loc:addresses>tel:+16472260233</loc:addresses>\n") .append(" <loc:senderName>6388</loc:senderName>\n") .append(" <loc:message>Test Message &</loc:message>\n").append(" </loc:sendSms>\n") .append(" </soapenv:Body>\n").append("</soapenv:Envelope>\n"); // startSmsNotification - place to deliver SMS to String req = string1.toString(); logger.debug("Request XML -> \n" + req); HttpPost post = new HttpPost(strURL); StringEntity postEntity = new StringEntity(req, "ISO-8859-1"); postEntity.setContentType("text/xml; charset=\"ISO-8859-1\""); post.addHeader("SOAPAction", "\"\""); post.setEntity(postEntity); long start = System.currentTimeMillis(); client.getCredentialsProvider().setCredentials(new AuthScope("209.226.31.233", AuthScope.ANY_PORT), new UsernamePasswordCredentials("Twitter", "Twitter123")); BasicHttpContext localcontext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local // execution context BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); // Add as the first request interceptor client.addRequestInterceptor(new PreemptiveAuth(), 0); HttpResponse httpResponse = client.execute(post, localcontext); HttpEntity responseEntity = httpResponse.getEntity(); // // was the request OK? // if (httpResponse.getStatusLine().getStatusCode() != 200) { logger.error("Request failed with StatusCode=" + httpResponse.getStatusLine().getStatusCode()); } // get an input stream String responseBody = EntityUtils.toString(responseEntity); long stop = System.currentTimeMillis(); logger.debug("----------------------------------------"); logger.debug("Response took " + (stop - start) + " ms"); logger.debug(responseBody); logger.debug("----------------------------------------"); // } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); }
From source file:org.aksw.simba.cetus.fox.FoxBasedTypeSearcher.java
public static void main(String[] args) throws UnsupportedCharsetException, ClientProtocolException, JSONException, IOException { Response response = Request.Post(FOX_SERVICE).addHeader("Content-type", "application/json") .addHeader("Accept-Charset", "UTF-8") .body(new StringEntity(new JSONObject().put("input", "Brian Banner is a fictional villain from the Marvel Comics Universe created by Bill Mantlo and Mike Mignola and first appearing in print in late 1985.") .put("type", "text").put("task", "ner").put("output", "JSON-LD").toString(), ContentType.APPLICATION_JSON)) .execute();/*from w w w . j a va 2s . c o m*/ HttpResponse httpResponse = response.returnResponse(); HttpEntity entry = httpResponse.getEntity(); String content = IOUtils.toString(entry.getContent(), "UTF-8"); System.out.println(content); }
From source file:io.kamax.mxisd.util.RestClientUtils.java
public static HttpPost post(String url, String body) { StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8); entity.setContentType(ContentType.APPLICATION_JSON.toString()); HttpPost req = new HttpPost(url); req.setEntity(entity);//from ww w .j a va 2 s . co m return req; }
From source file:com.fufang.httprequest.HttpPostBuild.java
public static String postBuildJson(String url, String params) throws UnsupportedEncodingException, ClientProtocolException, IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); String postResult = null;// w w w . j ava 2 s.c o m HttpPost httpPost = new HttpPost(url); System.out.println(" request " + httpPost.getRequestLine()); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000) .build(); httpPost.setConfig(requestConfig); StringEntity entity = new StringEntity(params.toString(), "UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); try { HttpResponse response = httpClient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity responseEntity = response.getEntity(); postResult = EntityUtils.toString(responseEntity); } else { System.out.println("unexpected response status - " + status); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return postResult; }
From source file:com.twitter.heron.integration_test.core.HttpUtils.java
static int httpJsonPost(String newHttpPostUrl, String jsonData) throws IOException, ParseException { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(newHttpPostUrl); StringEntity requestEntity = new StringEntity(jsonData, ContentType.APPLICATION_JSON); post.setEntity(requestEntity);/*from www. j a v a 2 s. c om*/ HttpResponse response = client.execute(post); return response.getStatusLine().getStatusCode(); }
From source file:io.amira.zen.json.ZenJson.java
private static StringEntity buildString(Object obj) { try {/* w ww .ja v a2 s . c om*/ return new StringEntity(obj.toString(), "UTF8"); } catch (Exception e) { return null; } }
From source file:su.fmi.photoshareclient.remote.LoginHandler.java
public static boolean login(String username, char[] password) { try {/*from w ww . java 2 s.c om*/ ProjectProperties properties = new ProjectProperties(); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost( "http://" + properties.get("socket") + properties.get("restEndpoint") + "/user/login"); StringEntity input = new StringEntity( "{\"username\":\"" + username + "\",\"password\":\"" + new String(password) + "\"}", ContentType.create("application/json")); post.setHeader("Content-Type", "application/json"); post.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(username, new String(password)), "UTF-8", false)); post.setEntity(input); if (username.isEmpty() || password.length == 0) { return false; } HttpResponse response = (HttpResponse) client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { String authString = username + ":" + new String(password); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); authStringEncr = new String(authEncBytes); return true; } else { return false; } } catch (UnsupportedEncodingException ex) { Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex); } return false; }