List of usage examples for org.apache.http.entity StringEntity setContentType
public void setContentType(Header header)
From source file:TestRESTPost12.java
public static void main(String[] p) throws Exception { String strurl = "http://localhost:8080/testnewmaven8/webresources/service/post"; //StringEntity str=new StringEntity("<a>hello post</a>",ContentType.create("application/xml" , Consts.UTF_8)); ///*from www . j a v a 2s.c om*/ StringEntity str = new StringEntity("hello post"); str.setContentType("APPLICATION/xml"); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(strurl); httppost.addHeader("Accept", "application/xml charset=UTF-8"); //httppost.addHeader("content_type", "application/xml, multipart/related"); httppost.setEntity(str); CloseableHttpResponse response = httpclient.execute(httppost); // try //{ int statuscode = response.getStatusLine().getStatusCode(); if (statuscode != 200) { System.out.println("http error occured=" + statuscode); } BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); while (br.readLine() != null) { System.out.println(br.readLine()); } // } /*catch(Exception e) { System.out.println("exception :"+e); }*/ //httpclient.close(); }
From source file:RestPostClient.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("http://localhost:10080/example/json/product/post"); StringEntity input = new StringEntity("{\"qty\":100,\"name\":\"iPad 4\"}"); input.setContentType("application/json"); postRequest.setEntity(input);//from www .j a v a2s . c o m HttpResponse response = httpClient.execute(postRequest); //if (response.getStatusLine().getStatusCode() != 201) { // throw new RuntimeException("Failed : HTTP error code : " // + 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:com.mycompany.horus.Teste.java
public static void main(String[] args) throws Exception { ServiceListener list = new ServiceListener(); list.getHorusServicesList();//from ww w . ja v a 2 s . c o m String soapBody = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:est=\"http://servicos.saude.gov.br/horus/v1r0/EstoqueService\">\n" + " <soap:Header>\n" + " <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wsswssecurity-secext-1.0.xsd\">\n" + " <wsse:UsernameToken wsu:Id=\"Id-0001334008436683-000000002c4a1908-1\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">\n" + " <wsse:Username>HORUS</wsse:Username>\n" + " <wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wssusername-token-profile-1.0#PasswordText\">SENHA</wsse:Password>\n" + " </wsse:UsernameToken>\n" + " </wsse:Security>\n" + " </soap:Header>\n" + " <soap:Body><est:requestConsultarPosicaoEstoquePorCNES>\n" + " <est:cnes>7604041</est:cnes>\n" + " </est:requestConsultarPosicaoEstoquePorCNES>\n" + " </soap:Body>\n" + "</soap:Envelope>\n"; try { // Get target URL CloseableHttpClient httpclient = HttpClientBuilder.create().build(); StringEntity strEntity = new StringEntity(soapBody, "UTF-8"); strEntity.setContentType("text/xml"); HttpPost post = new HttpPost("https://servicos.saude.gov.br/horus/v1r0/EstoqueService"); post.setEntity(strEntity); // Execute request HttpResponse response = httpclient.execute(post); HttpEntity respEntity = response.getEntity(); String resp = EntityUtils.toString(respEntity); if (respEntity != null) { System.out.println("Response:"); System.out.println(resp); //Changing response to Xml file stringToDom(resp); } else { System.out.println("No Response"); } } catch (Exception e) { System.out.println("Other exception = " + e.toString()); } }
From source file:com.cloudhopper.sxmp.PostMO.java
static public void main(String[] args) throws Exception { String URL = "https://sms.twitter.com/receive/cloudhopper"; String text = "HELP"; String srcAddr = "+16504304922"; String ticketId = System.currentTimeMillis() + ""; String operatorId = "20"; StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n") .append("<operation type=\"deliver\">\n") .append(" <account username=\"customer1\" password=\"password1\"/>\n").append(" <deliverRequest>\n") .append(" <operatorId>" + operatorId + "</operatorId>\n") .append(" <sourceAddress type=\"international\">" + srcAddr + "</sourceAddress>\n") .append(" <destinationAddress type=\"network\">40404</destinationAddress>\n") .append(" <text encoding=\"ISO-8859-1\">" + HexUtil.toHexString(text.getBytes()) + "</text>\n") .append(" </deliverRequest>\n").append("</operation>\n").append(""); HttpClient client = new DefaultHttpClient(); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); long start = System.currentTimeMillis(); // execute request try {/*from w w w .j a v a2 s . c om*/ HttpPost post = new HttpPost(URL); StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1"); entity.setContentType("text/xml; charset=\"ISO-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); logger.debug("----------------------------------------"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } long end = System.currentTimeMillis(); logger.debug("Response took " + (end - start) + " ms"); }
From source file:com.cloudhopper.sxmp.PostUTF8MO.java
static public void main(String[] args) throws Exception { String URL = "https://sms-staging.twitter.com/receive/cloudhopper"; // this is a Euro currency symbol //String text = "\u20AC"; // shorter arabic //String text = "\u0623\u0647\u0644\u0627"; // even longer arabic //String text = "\u0623\u0647\u0644\u0627\u0020\u0647\u0630\u0647\u0020\u0627\u0644\u062a\u062c\u0631\u0628\u0629\u0020\u0627\u0644\u0623\u0648\u0644\u0649"; String text = ""; for (int i = 0; i < 140; i++) { text += "\u0623"; }// w w w.ja v a2 s . c o m String srcAddr = "+14159129228"; String ticketId = System.currentTimeMillis() + ""; String operatorId = "23"; //text += " " + ticketId; StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n") .append("<operation type=\"deliver\">\n") .append(" <account username=\"customer1\" password=\"password1\"/>\n").append(" <deliverRequest>\n") .append(" <ticketId>" + ticketId + "</ticketId>\n") .append(" <operatorId>" + operatorId + "</operatorId>\n") .append(" <sourceAddress type=\"international\">" + srcAddr + "</sourceAddress>\n") .append(" <destinationAddress type=\"network\">40404</destinationAddress>\n") .append(" <text encoding=\"UTF-8\">" + HexUtil.toHexString(text.getBytes("UTF-8")) + "</text>\n") .append(" </deliverRequest>\n").append("</operation>\n").append(""); HttpClient client = new DefaultHttpClient(); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); long start = System.currentTimeMillis(); // execute request try { HttpPost post = new HttpPost(URL); StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1"); entity.setContentType("text/xml; charset=\"ISO-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); logger.debug("----------------------------------------"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } long end = System.currentTimeMillis(); logger.debug("Response took " + (end - start) + " ms"); }
From source file:com.cloudhopper.sxmp.SubmitMain.java
static public void main(String[] args) throws Exception { String url = "http://localhost:9080/api/sxmp/1.0"; // create a submit request SubmitRequest submit = new SubmitRequest(); submit.setAccount(new Account("customer1", "password1")); submit.setDeliveryReport(Boolean.TRUE); MobileAddress sourceAddr = new MobileAddress(); sourceAddr.setAddress(MobileAddress.Type.NETWORK, "40404"); submit.setSourceAddress(sourceAddr); submit.setOperatorId(24);/*from www .j a v a 2 s .c om*/ MobileAddress destAddr = new MobileAddress(); destAddr.setAddress(MobileAddress.Type.INTERNATIONAL, "+14155551212"); submit.setDestinationAddress(destAddr); submit.setText( "Test abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijbcdefghij", TextEncoding.UTF_8); //submit.setText("Hello World"); // Get file to be posted HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); long totalStart = System.currentTimeMillis(); int count = 1; for (int i = 0; i < count; i++) { long start = System.currentTimeMillis(); // execute request try { HttpPost post = new HttpPost(url); //ByteArrayEntity entity = new ByteArrayEntity(data); StringEntity entity = new StringEntity(SxmpWriter.createString(submit)); entity.setContentType("text/xml; charset=\"iso-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); long stop = System.currentTimeMillis(); logger.debug("----------------------------------------"); logger.debug("Response took " + (stop - start) + " ms"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } } long totalEnd = System.currentTimeMillis(); logger.debug("Response took " + (totalEnd - totalStart) + " ms for " + count + " requests"); double seconds = ((double) (totalEnd - totalStart)) / 1000; double smspersec = ((double) count) / seconds; logger.debug("SMS / Sec: " + DecimalUtil.toString(smspersec, 2)); }
From source file:com.cloudhopper.sxmp.Post.java
static public void main(String[] args) throws Exception { String message = "Test With @ Character"; //String message = "Tell Twitter what you're doing!\nStd msg charges apply. Send 'stop' to quit.\nVisit twitter.com or email help@twitter.com for help."; StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\"?>\n") .append("<operation type=\"submit\">\n") .append(" <account username=\"customer1\" password=\"password1\"/>\n") .append(" <submitRequest referenceId=\"MYREF102020022\">\n") .append(" <operatorId>75</operatorId>\n").append(" <deliveryReport>true</deliveryReport>\n") .append(" <sourceAddress type=\"network\">40404</sourceAddress>\n") .append(" <destinationAddress type=\"international\">+13135551234</destinationAddress>\n") .append(" <text encoding=\"ISO-8859-1\">" + HexUtil.toHexString(message.getBytes("ISO-8859-1")) + "</text>\n") .append(" </submitRequest>\n").append("</operation>\n").append(""); /**/*from w ww. j av a2 s .c o m*/ //.append("<!DOCTYPE chapter PUBLIC \"-//OASIS//DTD DocBook XML//EN\" \"../dtds/docbookx.dtd\">") //.append("<!DOCTYPE chapter PUBLIC \"-//OASIS//DTD DocBook XML//EN\">") .append("<submitRequest sequenceId=\"1000\">\n") .append(" <!-- this is a comment -->\n") .append(" <account username=\"testaccount\" password=\"testpassword\"/>\n") .append(" <option />\n") .append(" <messageRequest referenceId=\"MYMESSREF\">\n") //.append(" <sourceAddress>+13135551212</sourceAddress>\n") .append(" <destinationAddress>+13135551200</destinationAddress>\n") .append(" <text><![CDATA[Hello World]]></text>\n") .append(" </messageRequest>\n") .append("</submitRequest>") .append(""); */ // Get target URL String strURL = "http://localhost:9080/api/sxmp/1.0"; // Get file to be posted //String strXMLFilename = args[1]; //File input = new File(strXMLFilename); HttpClient client = new DefaultHttpClient(); long totalStart = System.currentTimeMillis(); for (int i = 0; i < 1; i++) { long start = System.currentTimeMillis(); // execute request try { HttpPost post = new HttpPost(strURL); StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1"); entity.setContentType("text/xml; charset=\"ISO-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); long stop = System.currentTimeMillis(); logger.debug("----------------------------------------"); logger.debug("Response took " + (stop - start) + " ms"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } } long totalEnd = System.currentTimeMillis(); logger.debug("Response took " + (totalEnd - totalStart) + " ms"); }
From source file:com.cloudhopper.sxmp.demo.SubmitMain.java
static public void main(String[] args) throws Exception { String url = "http://127.0.0.1:8080/api/sxmp/1.0"; String phone = "+14155551212"; int operator = 1; if (args.length > 0) url = args[0];// w w w . j a v a 2 s. co m if (args.length > 1) phone = args[1]; if (args.length > 2) operator = Integer.parseInt(args[2]); // create a submit request SubmitRequest submit = new SubmitRequest(); submit.setAccount(new Account("customer1", "password1")); submit.setDeliveryReport(Boolean.TRUE); MobileAddress sourceAddr = new MobileAddress(); sourceAddr.setAddress(MobileAddress.Type.NETWORK, "40404"); submit.setSourceAddress(sourceAddr); submit.setOperatorId(operator); submit.setPriority(Priority.URGENT); MobileAddress destAddr = new MobileAddress(); destAddr.setAddress(MobileAddress.Type.INTERNATIONAL, phone); submit.setDestinationAddress(destAddr); submit.setText("Hello World"); // Get file to be posted HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); long totalStart = System.currentTimeMillis(); int count = 1; for (int i = 0; i < count; i++) { long start = System.currentTimeMillis(); // execute request try { HttpPost post = new HttpPost(url); //ByteArrayEntity entity = new ByteArrayEntity(data); StringEntity entity = new StringEntity(SxmpWriter.createString(submit)); entity.setContentType("text/xml; charset=\"iso-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); long stop = System.currentTimeMillis(); logger.debug("----------------------------------------"); logger.debug("Response took " + (stop - start) + " ms"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } } long totalEnd = System.currentTimeMillis(); logger.debug("Response took " + (totalEnd - totalStart) + " ms for " + count + " requests"); double seconds = ((double) (totalEnd - totalStart)) / 1000; double smspersec = ((double) count) / seconds; logger.debug("SMS / Sec: " + DecimalUtil.toString(smspersec, 2)); }
From source file:com.cloudhopper.sxmp.DeliverMain.java
static public void main(String[] args) throws Exception { // create a deliver request DeliverRequest deliver = new DeliverRequest(); deliver.setAccount(new Account("customer1", "password1")); deliver.setOperatorId(2);// w w w . j av a 2 s . co m MobileAddress sourceAddr = new MobileAddress(); sourceAddr.setAddress(MobileAddress.Type.INTERNATIONAL, "+13135551212"); deliver.setSourceAddress(sourceAddr); MobileAddress destAddr = new MobileAddress(); destAddr.setAddress(MobileAddress.Type.NETWORK, "55555"); deliver.setDestinationAddress(destAddr); deliver.setText( "This is a new message that I want to send that's a little larger than normal &!#@%20*()$#@!~"); // target url //String url = "http://localhost:9080/api/sxmp/1.0"; //String url = "http://lyn-stratus-001/api/sxmp/1.0"; //String url = "http://localhost:9080/api/sxmp/1.0"; //String strURL = "http://sfd-twtr-gw.cloudhopper.com/api/sxmp/1.0"; String url = "http://lyn-stratus-lab5:9080/api/sxmp/1.0"; // Get file to be posted HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); // convert request into a byte array //byte[] data = SxmpWriter.createByteArray(submit); //logger.debug(StringUtil.toHexString(data)); long totalStart = System.currentTimeMillis(); int count = 5000; for (int i = 0; i < count; i++) { long start = System.currentTimeMillis(); // execute request try { HttpPost post = new HttpPost(url); //ByteArrayEntity entity = new ByteArrayEntity(data); StringEntity entity = new StringEntity(SxmpWriter.createString(deliver)); entity.setContentType("text/xml; charset=\"iso-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); long stop = System.currentTimeMillis(); logger.debug("----------------------------------------"); logger.debug("Response took " + (stop - start) + " ms"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } } long totalEnd = System.currentTimeMillis(); logger.debug("Response took " + (totalEnd - totalStart) + " ms for " + count + " requests"); double seconds = ((double) (totalEnd - totalStart)) / 1000; double smspersec = ((double) count) / seconds; logger.debug("SMS / Sec: " + DecimalUtil.toString(smspersec, 2)); }
From source file:test.TestJavaService.java
/** * Main. The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag. If it is specified, * we test code on the AWS instance. If it is not, we test code running locally. * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file * org.qcert.javasrc.Main. Remaining non-flag arguments are file names. There must be at least one. The number of such * arguments and what they should contain depends on the verb. * @throws Exception/* w w w .java 2 s . c o m*/ */ public static void main(String[] args) throws Exception { /* Parse command line */ List<String> files = new ArrayList<>(); String loc = "localhost", verb = null; for (String arg : args) { if (arg.equals("-remote")) loc = REMOTE_LOC; else if (arg.startsWith("-")) illegal(); else if (verb == null) verb = arg; else files.add(arg); } /* Simple consistency checks and verb-specific parsing */ if (files.size() == 0) illegal(); String file = files.remove(0); String schema = null; switch (verb) { case "parseSQL": case "serialRule2CAMP": case "sqlSchema2JSON": if (files.size() != 0) illegal(); break; case "techRule2CAMP": if (files.size() != 1) illegal(); schema = files.get(0); break; case "csv2JSON": if (files.size() < 1) illegal(); break; default: illegal(); } /* Assemble information from arguments */ String url = String.format("http://%s:9879?verb=%s", loc, verb); byte[] contents = Files.readAllBytes(Paths.get(file)); String toSend; if ("serialRule2CAMP".equals(verb)) toSend = Base64.getEncoder().encodeToString(contents); else toSend = new String(contents); if ("techRule2CAMP".equals(verb)) toSend = makeSpecialJson(toSend, schema); else if ("csv2JSON".equals(verb)) toSend = makeSpecialJson(toSend, files); HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(toSend); entity.setContentType("text/plain"); post.setEntity(entity); HttpResponse resp = client.execute(post); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { HttpEntity answer = resp.getEntity(); InputStream s = answer.getContent(); BufferedReader rdr = new BufferedReader(new InputStreamReader(s)); String line = rdr.readLine(); while (line != null) { System.out.println(line); line = rdr.readLine(); } rdr.close(); s.close(); } else System.out.println(resp.getStatusLine()); }