List of usage examples for org.apache.http.client HttpClient execute
HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException;
From source file:at.orz.arangodb.sandbox.PostChunkTest.java
/** * @param args/*from ww w . java 2s. c o m*/ */ public static void main(String[] args) throws Exception { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost( "http://arango-test-server:9999/_api/import?collection=test1&createCollection=true&type=documents"); //post.setEntity(new StringEntity("{\"xx\": \"123\"}{\"xx\": \"456\"}")); InputStreamEntity entity = new InputStreamEntity( new ByteArrayInputStream("{\"xx\": \"123\"}{\"xx\": \"456\"}".getBytes()), 26); entity.setChunked(true); post.setEntity(entity); HttpResponse res = client.execute(post); System.out.println(res.getStatusLine()); post.releaseConnection(); }
From source file:org.salever.rcp.remoteSystem.server.util.ClientAbortMethod.java
public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); try {//from w w w .jav a2s. c o m String queryString = "wd=?ddd="; String decodeUrl = URLEncoder.encode(queryString, "GBK"); String string = new String(decodeUrl); System.out.println("--------------" + string + "--------------------------"); HttpGet httpget = new HttpGet("http://www.baidu.com/s?" + string); System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); String line; while ((line = reader.readLine()) != null) { // System.out.println(line); } } System.out.println("----------------------------------------"); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:org.vuphone.vandyupon.test.EventRatingRequestTest.java
public static void main(String[] args) { HttpClient c = new DefaultHttpClient(); HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); String params = "type=eventpost&eventname=Test&starttime=" + System.currentTimeMillis() + "&endtime=" + (System.currentTimeMillis() + 6000000) + "&userid=chris&resp=xml&desc=a%20new%20event&locationlat=36.1437&locationlon=-86.8046"; post.setEntity(new ByteArrayEntity(params.toString().getBytes())); try {/*from w w w . j a v a2s.c o m*/ HttpResponse resp = c.execute(post); resp.getEntity().writeTo(System.out); } catch (IOException e) { e.printStackTrace(); } }
From source file:nl.raja.niruraji.pa.PlayGround.java
public static void main(String[] args) { try {//from w w w.j a v a 2s . com // create HTTP Client HttpClient httpClient = HttpClientBuilder.create().build(); String url = "http://buienradar.nl/Json/GetTwentyFourHourForecast?geolocationid=2751773"; // Create new getRequest with below mentioned URL HttpGet getRequest = new HttpGet(url); // Add additional header to getRequest which accepts application/xml data //getRequest.addHeader("accept", "application/xml"); // Execute your request and catch response HttpResponse response = httpClient.execute(getRequest); // Check for HTTP response code: 200 = success if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } String result = EntityUtils.toString(response.getEntity()); JSONObject myObject = new JSONObject(result); // Get-Capture Complete application/xml body response BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("============Output:============"); // Simply iterate through XML response and show on console. while ((output = br.readLine()) != null) { System.out.println(output); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.openeclass.EclassMobile.java
public static void main(String[] args) { try {/* w w w . j ava2 s . co m*/ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://myeclass/modules/mobile/mlogin.php"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("uname", mUsername)); nvps.add(new BasicNameValuePair("pass", mPassword)); httppost.setEntity(new UrlEncodedFormEntity(nvps)); System.out.println("twra tha kanei add"); System.out.println("prin to response"); HttpResponse response = httpclient.execute(httppost); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) System.out.println("Invalid response from server: " + status.toString()); System.out.println("meta to response"); Header[] head = response.getAllHeaders(); for (int i = 0; i < head.length; i++) System.out.println("to head exei " + head[i]); System.out.println("Login form get: " + response.getStatusLine()); HttpEntity entity = response.getEntity(); InputStream ips = entity.getContent(); BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8"), 1024); StringBuilder sb = new StringBuilder(); String s = ""; while ((s = buf.readLine()) != null) { sb.append(s); } System.out.println("to sb einai " + sb.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:httpclient.entity.mime.ClientMultipartFormPost.java
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1);// w ww .j a v a 2 s .c o m } HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); // reqEntity.addPart("bin", bin); // reqEntity.addPart("comment", comment); // httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } if (resEntity != null) { resEntity.consumeContent(); } }
From source file:org.wso2.carbon.sample.http.Http.java
public static void main(String args[]) { log.info("Starting WSO2 Http Client"); HttpUtil.setTrustStoreParams();// w w w. java2 s . c o m String url = args[0]; String username = args[1]; String password = args[2]; String sampleNumber = args[3]; String filePath = args[4]; HttpClient httpClient = new SystemDefaultHttpClient(); try { HttpPost method = new HttpPost(url); filePath = HttpUtil.getMessageFilePath(sampleNumber, filePath, url); readMsg(filePath); for (String message : messagesList) { StringEntity entity = new StringEntity(message); log.info("Sending message:"); log.info(message + "\n"); method.setEntity(entity); if (url.startsWith("https")) { processAuthentication(method, username, password); } httpClient.execute(method).getEntity().getContent().close(); } Thread.sleep(500); // Waiting time for the message to be sent } catch (Throwable t) { log.error("Error when sending the messages", t); } }
From source file:com.dlmu.heipacker.crawler.examples.entity.mime.ClientMultipartFormPost.java
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1);// ww w .j a va 2s . com } HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost( "http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }
From source file:com.thed.zapi.cloud.sample.CreateTestWithTestSteps.java
public static void main(String[] args) throws JSONException, URISyntaxException, ParseException, IOException { final String createTestUri = API_CREATE_TEST.replace("{SERVER}", jiraBaseURL); final String createTestStepUri = API_CREATE_TEST_STEP.replace("{SERVER}", zephyrBaseUrl); /**/*from w ww .j a va2 s. c o m*/ * Create Test Parameters, declare Create Test Issue fields Declare more * field objects if required */ JSONObject projectObj = new JSONObject(); projectObj.put("id", projectId); // Project ID where the Test to be // Created JSONObject issueTypeObj = new JSONObject(); issueTypeObj.put("id", issueTypeId); // IssueType ID which is Test isse // type JSONObject assigneeObj = new JSONObject(); assigneeObj.put("name", userName); // Username of the assignee JSONObject reporterObj = new JSONObject(); reporterObj.put("name", userName); // Username of the Reporter String testSummary = "Sample Test case With Steps created through ZAPI Cloud"; // Test // Case // Summary/Name /** * Create JSON payload to POST Add more field objects if required * * ***DONOT EDIT BELOW *** */ JSONObject fieldsObj = new JSONObject(); fieldsObj.put("project", projectObj); fieldsObj.put("summary", testSummary); fieldsObj.put("issuetype", issueTypeObj); fieldsObj.put("assignee", assigneeObj); fieldsObj.put("reporter", reporterObj); JSONObject createTestObj = new JSONObject(); createTestObj.put("fields", fieldsObj); System.out.println(createTestObj.toString()); byte[] bytesEncoded = Base64.encodeBase64((userName + ":" + password).getBytes()); String authorizationHeader = "Basic " + new String(bytesEncoded); Header header = new BasicHeader(HttpHeaders.AUTHORIZATION, authorizationHeader); StringEntity createTestJSON = null; try { createTestJSON = new StringEntity(createTestObj.toString()); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } HttpResponse response = null; HttpClient restClient = new DefaultHttpClient(); try { // System.out.println(issueSearchURL); HttpPost createTestReq = new HttpPost(createTestUri); createTestReq.addHeader(header); createTestReq.addHeader("Content-Type", "application/json"); createTestReq.setEntity(createTestJSON); response = restClient.execute(createTestReq); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String testId = null; int statusCode = response.getStatusLine().getStatusCode(); // System.out.println(statusCode); HttpEntity entity1 = response.getEntity(); if (statusCode >= 200 && statusCode < 300) { String string1 = null; try { string1 = EntityUtils.toString(entity1); System.out.println(string1); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } JSONObject createTestResp = new JSONObject(string1); testId = createTestResp.getString("id"); System.out.println("testId :" + testId); } else { try { String string = null; string = EntityUtils.toString(entity1); JSONObject executionResponseObj = new JSONObject(string); System.out.println(executionResponseObj.toString()); throw new ClientProtocolException("Unexpected response status: " + statusCode); } catch (ClientProtocolException e) { e.printStackTrace(); } } /** Create test Steps ***/ /** * Create Steps Replace the step,data,result values as required */ JSONObject testStepJsonObj = new JSONObject(); testStepJsonObj.put("step", "Sample Test Step"); testStepJsonObj.put("data", "Sample Test Data"); testStepJsonObj.put("result", "Sample Expected Result"); /** DONOT EDIT FROM HERE ***/ StringEntity createTestStepJSON = null; try { createTestStepJSON = new StringEntity(testStepJsonObj.toString()); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String finalURL = createTestStepUri + testId + "?projectId=" + projectId; URI uri = new URI(finalURL); int expirationInSec = 360; JwtGenerator jwtGenerator = client.getJwtGenerator(); String jwt = jwtGenerator.generateJWT("POST", uri, expirationInSec); System.out.println(uri.toString()); System.out.println(jwt); HttpResponse responseTestStep = null; HttpPost addTestStepReq = new HttpPost(uri); addTestStepReq.addHeader("Content-Type", "application/json"); addTestStepReq.addHeader("Authorization", jwt); addTestStepReq.addHeader("zapiAccessKey", accessKey); addTestStepReq.setEntity(createTestStepJSON); try { responseTestStep = restClient.execute(addTestStepReq); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int testStepStatusCode = responseTestStep.getStatusLine().getStatusCode(); System.out.println(testStepStatusCode); System.out.println(response.toString()); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = responseTestStep.getEntity(); String string = null; String stepId = null; try { string = EntityUtils.toString(entity); JSONObject testStepObj = new JSONObject(string); stepId = testStepObj.getString("id"); System.out.println("stepId :" + stepId); System.out.println(testStepObj.toString()); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { try { throw new ClientProtocolException("Unexpected response status: " + statusCode); } catch (ClientProtocolException e) { e.printStackTrace(); } } }
From source file:org.dineth.shooter.client.Example.java
public static void main(String[] args) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:8080/upload"); filename = "router.jpg"; FileBody bin = new FileBody(new File(filename)); StringBody fileName = null;/* www.j a v a 2 s .c o m*/ try { fileName = new StringBody(filename); } catch (UnsupportedEncodingException ex) { Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex); } MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", bin); reqEntity.addPart("filename", fileName); httppost.setEntity(reqEntity); HttpResponse response = null; try { response = httpclient.execute(httppost); } catch (IOException ex) { Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex); } HttpEntity resEntity = response.getEntity(); }