List of usage examples for org.apache.http.client ClientProtocolException ClientProtocolException
public ClientProtocolException(final Throwable cause)
From source file:net.airvantage.sample.AirVantageExampleFlow2.java
public static void main(String[] args) { String apiUrl = "https://na.airvantage.net/api"; // Replace these with your own api key and secret String apiKey = "your_app_id"; String apiSecret = "your_api_secret"; String login = null;/*from w ww .java 2 s. c om*/ String password = null; String access_token = null; Scanner in = new Scanner(System.in); System.out.println("=== AirVantage's OAuth Workflow ==="); System.out.println(); // Obtain User/Password System.out.println("Enter your login:"); System.out.print(">>"); login = in.nextLine(); System.out.println(); System.out.println("...and your password:"); System.out.print(">>"); password = in.nextLine(); System.out.println(); // Get the Access Token System.out.println("Getting the Access Token..."); System.out.println(apiUrl + "/oauth/token?grant_type=password&username=" + login + "&password=" + password + "&client_id=" + apiKey + "&client_secret=" + apiSecret); try { access_token = Request .Get(apiUrl + "/oauth/token?grant_type=password&username=" + login + "&password=" + password + "&client_id=" + apiKey + "&client_secret=" + apiSecret) .execute().handleResponse(new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); } try { String content = IOUtils.toString(entity.getContent()); JSONObject result = new JSONObject(content); return result.getString("access_token"); } catch (JSONException e) { throw new ClientProtocolException("Malformed JSON", e); } } }); System.out.println("Got the Access Token!"); System.out.println("(if you're curious it looks like this: " + access_token + " )"); System.out.println(); // Now let's go and ask for a protected resource! System.out.println("Now we're going to get info about the current user..."); JSONObject result = Request.Get(apiUrl + "/v1/users/current?access_token=" + access_token).execute() .handleResponse(new ResponseHandler<JSONObject>() { public JSONObject handleResponse(final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); } try { String content = IOUtils.toString(entity.getContent()); return new JSONObject(content); } catch (JSONException e) { throw new ClientProtocolException("Malformed JSON", e); } } }); System.out.println("Got it! Let's see what we found..."); System.out.println(); System.out.println(result.toString()); System.out.println(); System.out.println("That's it man! Go and build something awesome with AirVantage! :)"); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:ClientWithResponseHandlerPost.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from w ww. jav a 2 s. c o m*/ List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("id", "KYacxNZ6QQc")); formparams.add(new BasicNameValuePair("calid", "adamm")); formparams.add(new BasicNameValuePair("content-out", "text/xml")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); //entity.setChunked(true); HttpPost httppost = new HttpPost("http://localhost:8080/export.wcap"); httppost.setEntity(entity); System.out.println("executing request " + httppost.getURI()); System.out.println("executing request " + httppost.getConfig()); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 600) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpclient.execute(httppost, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); System.out.println("----------------------------------------"); } finally { httpclient.close(); } }
From source file:org.apache.http.examples.client.ClientWithResponseHandlerForUms.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); // DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); // httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); try {/*w ww .j ava2s.co m*/ // String url = "http://mxyinghang.com/pay/ums/umsLogin.htm"; String url = "http://cs.com:8080/web/ums/verify"; HttpGet httpget = new HttpGet(url); httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch"); httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8"); httpget.setHeader("Cache-Control", "no-cache"); httpget.setHeader("Connection", "keep-alive"); httpget.setHeader("Referer", "http://mxyinghang.com/richboss/"); httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36"); System.out.println("Executing request httpget.getRequestLine() " + httpget.getRequestLine()); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity, "utf-8") : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpclient.execute(httpget, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); System.out.println("----------------------------------------"); // ObjectMapper mapper = new ObjectMapper(); // mapper.readValue(responseBody, AddressCoord.class); // JsonNode root = mapper.readTree(responseBody.substring("showLocation&&showLocation(".length(), responseBody.length()-1)); } finally { httpclient.close(); } }
From source file:io.aos.protocol.http.httpcommon.FluentResponseHandling.java
public static void main(String... args) throws Exception { Document result = Request.Get("http://somehost/content").execute() .handleResponse(new ResponseHandler<Document>() { public Document handleResponse(final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); }/*www . j a v a 2s .c o m*/ if (entity == null) { throw new ClientProtocolException("Response contains no content"); } DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); try { DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); ContentType contentType = ContentType.getOrDefault(entity); if (!contentType.equals(ContentType.APPLICATION_XML)) { throw new ClientProtocolException("Unexpected content type:" + contentType); } Charset charset = contentType.getCharset(); if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } return docBuilder.parse(entity.getContent(), charset.name()); } catch (ParserConfigurationException ex) { throw new IllegalStateException(ex); } catch (SAXException ex) { throw new ClientProtocolException("Malformed XML document", ex); } } }); // Do something useful with the result System.out.println(result); }
From source file:org.apache.http.examples.client.ClientWithResponseHandler.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); // DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); // httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); try {//ww w . ja v a2 s . c o m // HttpGet httpget = new HttpGet("http://localhost/"); HttpGet httpget = new HttpGet( "http://api.map.baidu.com/geocoder/v2/?address=&output=json&ak=E4805d16520de693a3fe707cdc962045&callback=showLocation"); // httpget.setHeader("Accept", "180.97.33.90:80"); httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch"); httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8"); httpget.setHeader("Cache-Control", "no-cache"); httpget.setHeader("Connection", "keep-alive"); httpget.setHeader("Referer", "http://developer.baidu.com/map/index.php?title=webapi/guide/changeposition"); httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36"); System.out.println("Executing request httpget.getRequestLine() " + httpget.getRequestLine()); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity, "utf-8") : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpclient.execute(httpget, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); //showLocation&&showLocation({"status":0,"result":{"location":{"lng":112.25009284837,"lat":32.229168591538},"precise":0,"confidence":14,"level":"\u533a\u53bf"}}) System.out.println("----------------------------------------"); ObjectMapper mapper = new ObjectMapper(); // mapper.readValue(responseBody, AddressCoord.class); JsonNode root = mapper.readTree( responseBody.substring("showLocation&&showLocation(".length(), responseBody.length() - 1)); // String name = root.get("name").asText(); // int age = root.get("age").asInt(); String status = root.get("status").asText(); String lng = root.with("result").with("location").get("lng").asText(); String lat = root.with("result").with("location").get("lat").asText(); String level = root.with("result").get("level").asText(); System.out.println(String.format("'%1$s': [%2$s, %3$s], status: %4$s", level, lng, lat, status)); } finally { httpclient.close(); } }
From source file:cn.jumper.study.http.ClientFormLogin.java
public static void main(String[] args) throws Exception { BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); HttpHost proxy = new HttpHost("192.168.10.3", 8080, "http"); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); try {/*from w ww. ja v a 2 s .c om*/ HttpGet httpget = new HttpGet("http://www.ksf-food.com/admin/Login.asp"); httpget.setConfig(config); CloseableHttpResponse response1 = httpclient.execute(httpget); try { HttpEntity entity = response1.getEntity(); System.out.println("Login form get: " + response1.getStatusLine()); EntityUtils.consume(entity); System.out.println("Initial set of cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { response1.close(); } String code = ""; try { HttpUriRequest httpgetCode = RequestBuilder.get() .setUri("http://www.ksf-food.com/admin/inc/checkcode.asp").setConfig(config).build(); /* * HttpGet httpgetCode = new HttpGet( * "http://www.qufuev.com/admin/inc/checkcode.asp"); * httpgetCode.setConfig(config); */ System.out.println("Executing request " + httpgetCode.getRequestLine()); System.out.println("========================================================"); System.out.println("==httpget header =="); for (Header header : httpgetCode.getAllHeaders()) { System.out.println(header.getName() + ":" + header.getValue()); } System.out.println("==httpget header =="); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); System.out.println("==respons header =="); for (Header header : response.getAllHeaders()) { System.out.println(header.getName() + ":" + header.getValue()); } System.out.println("==respons header =="); String fileName = System.currentTimeMillis() + ""; DataOutputStream dataOutputStream = new DataOutputStream( new FileOutputStream("d://test//e3//" + fileName + ".jpg")); dataOutputStream.write(EntityUtils.toByteArray(entity)); dataOutputStream.close(); return ImageTest.getAllOcr("d://test//e3//" + fileName + ".jpg"); } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; code = httpclient.execute(httpgetCode, responseHandler); System.out.println("ClientFormLogin.main()-CheckCode:" + code); System.out.println("----------------------------------------"); } catch (IOException e) { e.printStackTrace(); } HttpUriRequest login = RequestBuilder.post() .setUri(new URI("http://www.ksf-food.com/admin/Admin_ChkLogin.asp")) .addParameter("UserName", "username").addParameter("Password", "password") .addParameter("CheckCode", code).setConfig(config).build(); System.out.println("========================================================"); System.out.println("==httpget header =="); for (Header header : login.getAllHeaders()) { System.out.println(header.getName() + ":" + header.getValue()); } CloseableHttpResponse response2 = httpclient.execute(login); try { HttpEntity entity = response2.getEntity(); System.out.println("Login form post: " + response2.getStatusLine()); // EntityUtils.consume(entity); System.out.println("ClientFormLogin.main():\\n" + EntityUtils.toString(entity, "GBK")); System.out.println("Post logon cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { response2.close(); } } finally { httpclient.close(); } }
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); /**//ww w . j av a 2 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:Main.java
protected static synchronized InputStream getAWebPage(URL url) throws ClientProtocolException, IOException { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet(url.toString()); try {/* ww w. jav a2 s .c om*/ //do the request HttpResponse response = httpClient.execute(httpGet, localContext); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HTTP_STATUS_OK) { throw new IOException("Invalid response from the IKSU server! " + status.toString()); } //InputStream ist = response.getEntity().getContent(); return response.getEntity().getContent(); } catch (Exception e) { e.printStackTrace(); throw new ClientProtocolException("Protocol Exception! " + e.toString()); } }
From source file:com.qwarz.graph.process.GraphProcess.java
/** * @param server/*from w ww. ja va2 s .c om*/ * @return the right implementation * @throws IOException * @throws URISyntaxException * @throws ServerException */ private static GraphProcessInterface getImplementation(ServerResource server) throws IOException, URISyntaxException, ServerException { if (server == null) throw new ClientProtocolException("The server to used has not been configured."); switch (server.getVersionOfDefault()) { case 1: return new GraphProcess1Impl(server); case 2: return new GraphProcess2Impl(); } throw new ServerException(Status.BAD_REQUEST, "Version not supported: " + server.version); }
From source file:it.av.wikipedia.client.WikipediaClient.java
public static String Query(QueryParameters params) { try (CloseableHttpClient httpclient = HttpClients.custom() .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()) .build()) {// www . ja v a 2 s .co m StringBuilder url = new StringBuilder(ENDPOINT); url.append(params.toURLQueryString()); //System.out.println("GET: " + url); HttpGet request = new HttpGet(url.toString()); request.setHeader("User-Agent", "FACWikiTool"); // Create a custom response handler ResponseHandler<String> responseHandler = (final HttpResponse response) -> { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } }; return httpclient.execute(request, responseHandler); } catch (IOException ex) { Logger.getLogger(WikipediaClient.class.getName()).log(Level.SEVERE, null, ex); return null; } }