List of usage examples for org.apache.http.client ClientProtocolException printStackTrace
public void printStackTrace()
From source file:br.unicamp.busfinder.ServerOperations.java
public static JSONArray getJSON(String site) { Log.d("Executing REquest", site); StringBuilder builder = new StringBuilder(); HttpGet get = new HttpGet(site); HttpClient client = new DefaultHttpClient(); HttpResponse response;//from w ww . j a v a 2 s .c o m try { response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e("ERRRO", "Failed to download file"); } Log.d("RESP:", builder.toString()); return new JSONArray(builder.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; }
From source file:fi.tuukka.weather.utils.Utils.java
public static String downloadHtml(String url) throws IllegalStateException { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url.toLowerCase()); HttpResponse response = null;/*from ww w . jav a 2 s .com*/ InputStream in = null; try { response = client.execute(request); in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder str = new StringBuilder(); String line = null; line = reader.readLine(); while (line != null) { str.append(line); try { line = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } } in.close(); return str.toString(); } catch (ClientProtocolException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return null; }
From source file:gov.in.bloomington.georeporter.models.Open311.java
/** * @param service_code// w ww. j a v a 2s . c o m * @return * JSONObject */ public static JSONObject getServiceDefinition(String service_code) { try { return new JSONObject(loadStringFromUrl(getServiceDefinitionUrl(service_code))); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:DeliverWork.java
private static String saveIntoWeed(RemoteFile remoteFile, String projectId) throws SQLException, UnsupportedEncodingException { String url = "http://59.215.226.174/WebDiskServerDemo/doc?doc_id=" + URLEncoder.encode(remoteFile.getFileId(), "utf-8"); CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; String res = ""; try {// ww w . ja v a 2s . c o m httpClient = HttpClients.createSystem(); // http(get?) HttpGet httpget = new HttpGet(url); response = httpClient.execute(httpget); HttpEntity result = response.getEntity(); String fileName = remoteFile.getFileName(); FileHandleStatus fileHandleStatus = getFileTemplate().saveFileByStream(fileName, new ByteArrayInputStream(EntityUtils.toByteArray(result))); System.out.println(fileHandleStatus); File file = new File(); if (result != null && result.getContentType() != null && result.getContentType().getValue() != null) { file.setContentType(result.getContentType().getValue()); } else { file.setContentType("application/error"); } file.setDataId(Integer.parseInt(projectId)); file.setName(fileName); if (fileName.contains(".bmp") || fileName.contains(".jpg") || fileName.contains(".jpeg") || fileName.contains(".png") || fileName.contains(".gif")) { file.setType(1); } else if (fileName.contains(".doc") || fileName.contains(".docx")) { file.setType(2); } else if (fileName.contains(".xlsx") || fileName.contains("xls")) { file.setType(3); } else if (fileName.contains(".pdf")) { file.setType(4); } else { file.setType(5); } String accessUrl = "/" + fileHandleStatus.getFileId().replaceAll(",", "/").concat("/").concat(fileName); file.setUrl(accessUrl); file.setSize(fileHandleStatus.getSize()); file.setPostTime(new java.util.Date()); file.setStatus(0); file.setEnumValue(findFileType(remoteFile.getFileType())); file.setResources(1); // JdbcFactory jdbcFactoryChanye=new JdbcFactory("jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8","root","111111","com.mysql.jdbc.Driver"); // Connection connection = jdbcFactoryChanye.getConnection(); DatabaseMetaData dmd = connection.getMetaData(); PreparedStatement ps = connection.prepareStatement(insertFile, new String[] { "ID" }); ps.setString(1, sdf.format(file.getPostTime())); ps.setInt(2, file.getType()); ps.setString(3, file.getEnumValue()); ps.setInt(4, file.getDataId()); ps.setString(5, file.getUrl()); ps.setString(6, file.getName()); ps.setString(7, file.getContentType()); ps.setLong(8, file.getSize()); ps.setInt(9, file.getStatus()); ps.setInt(10, file.getResources()); ps.executeUpdate(); if (dmd.supportsGetGeneratedKeys()) { ResultSet rs = ps.getGeneratedKeys(); while (rs.next()) { System.out.println(rs.getLong(1)); } } ps.close(); res = "success"; } catch (ClientProtocolException e) { e.printStackTrace(); res = e.getMessage(); } catch (IOException e) { e.printStackTrace(); res = e.getMessage(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (httpClient != null) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } if (response != null) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } return res; }
From source file:com.mingsoft.util.proxy.Proxy.java
/** * get//from w ww . j a v a 2 s . c o m * * @param url * ?<br> * @param header * ?Header new Header()<br> * @param params * ?<br> * @return Result */ public static Result get(String url, com.mingsoft.util.proxy.Header header, Map params) { //log.info("?" + url); // Httpclient DefaultHttpClient client = new DefaultHttpClient(); // ?? url = url + (null == params ? "" : assemblyParameter(params)); // get HttpGet httpGet = new HttpGet(url); // cookie?() httpGet.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); // ? if (null != header && header.getHeaders().size() > 0) { httpGet.setHeaders(Proxy.assemblyHeader(header.getHeaders())); } // ?HttpResponse HttpResponse response; try { response = client.execute(httpGet); // // httpGet.abort(); // HttpEntity HttpEntity entity = response.getEntity(); // ?? Result result = new Result(); // cookie result.setCookie(assemblyCookie(client.getCookieStore().getCookies())); // ? result.setStatusCode(response.getStatusLine().getStatusCode()); // result.setHeaders(response.getAllHeaders()); // ? result.setHttpEntity(entity); return result; } catch (ClientProtocolException e) { e.printStackTrace(); log.error(e.getMessage()); } catch (IOException e) { e.printStackTrace(); log.error(e.getMessage()); } return null; }
From source file:com.mingsoft.util.proxy.Proxy.java
/** * get??/*from w w w . j a v a2 s. co m*/ * * @param url * ?<br> * @param fileUrl * ????<br> * @param header * ?Header new Header()<br> */ public static void getRandCode(String url, com.mingsoft.util.proxy.Header header, String fileUrl) { DefaultHttpClient client = new DefaultHttpClient(); //log.info("?" + url); // get HttpGet get = new HttpGet(url); // cookie?() get.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); Map _headers = header.getHeaders(); // ? if (null != header && _headers.size() > 0) { get.setHeaders(Proxy.assemblyHeader(_headers)); } HttpResponse response; try { response = client.execute(get); // ? // Header[] h = (Header[]) response.getAllHeaders(); // for (int i = 0; i < h.length; i++) { // Header a = h[i]; // } HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); // cookie???cookie header.setCookie(assemblyCookie(client.getCookieStore().getCookies())); int temp = 0; // File file = new File(fileUrl); // ?? FileOutputStream out = new FileOutputStream(file); while ((temp = in.read()) != -1) { out.write(temp); } in.close(); out.close(); } catch (ClientProtocolException e) { e.printStackTrace(); log.error(e.getMessage()); } catch (IOException e) { e.printStackTrace(); log.error(e.getMessage()); } }
From source file:com.thed.zapi.cloud.sample.FetchExecuteUpdate.java
public static void addTestsToCycle(String uriStr, ZFJCloudRestClient client, String accessKey, StringEntity addTestsJSON) throws URISyntaxException, JSONException { URI uri = new URI(uriStr); int expirationInSec = 360; JwtGenerator jwtGenerator = client.getJwtGenerator(); String jwt = jwtGenerator.generateJWT("POST", uri, expirationInSec); // System.out.println(uri.toString()); // System.out.println(jwt); HttpResponse response = null;// w w w . ja v a 2s. co m HttpClient restClient = new DefaultHttpClient(); HttpPost addTestsReq = new HttpPost(uri); addTestsReq.addHeader("Content-Type", "application/json"); addTestsReq.addHeader("Authorization", jwt); addTestsReq.addHeader("zapiAccessKey", accessKey); addTestsReq.setEntity(addTestsJSON); try { response = restClient.execute(addTestsReq); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int statusCode = response.getStatusLine().getStatusCode(); // System.out.println(statusCode); // System.out.println(response.toString()); if (statusCode >= 200 && statusCode < 300) { System.out.println("Tests added Successfully"); } else { try { throw new ClientProtocolException("Unexpected response status: " + statusCode); } catch (ClientProtocolException e) { e.printStackTrace(); } } }
From source file:com.mywork.framework.util.RemoteHttpUtil.java
/** * ?? Post/*from ww w . java2s . c o m*/ * @return */ public static String doPost(String contentUrl, Map<String, String> headerMap, String jsonBody) { String result = null; CloseableHttpResponse response = null; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(contentUrl); RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_SECONDS * 1000) .setConnectTimeout(TIMEOUT_SECONDS * 1000).setSocketTimeout(TIMEOUT_SECONDS * 1000).build(); post.setConfig(config); try { if (headerMap != null && !headerMap.isEmpty()) { for (Map.Entry<String, String> m : headerMap.entrySet()) { post.setHeader(m.getKey(), m.getValue()); } } if (jsonBody != null) { StringEntity entity = new StringEntity(jsonBody, "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); } long start = System.currentTimeMillis(); response = httpClient.execute(post); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); logger.info("url = " + contentUrl + " request spend time = " + (System.currentTimeMillis() - start)); EntityUtils.consume(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
From source file:com.thed.zapi.cloud.sample.FetchExecuteUpdate.java
private static String[] getIssuesByJQL(String issueSearchURL, String userName, String password, JSONObject jqlJsonObj) throws JSONException { byte[] bytesEncoded = Base64.encodeBase64((userName + ":" + password).getBytes()); String authorizationHeader = "Basic " + new String(bytesEncoded); Header header = new BasicHeader(HttpHeaders.AUTHORIZATION, authorizationHeader); String[] issueIds = new String[jqlJsonObj.getInt("maxResults")]; StringEntity jqlJSON = null;/*from www .j a v a 2 s. c o m*/ try { jqlJSON = new StringEntity(jqlJsonObj.toString()); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } HttpResponse response = null; HttpClient restClient = new DefaultHttpClient(); try { // System.out.println(issueSearchURL); HttpPost createProjectReq = new HttpPost(issueSearchURL); createProjectReq.addHeader(header); createProjectReq.addHeader("Content-Type", "application/json"); createProjectReq.setEntity(jqlJSON); response = restClient.execute(createProjectReq); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int statusCode = response.getStatusLine().getStatusCode(); // System.out.println(statusCode); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity1 = response.getEntity(); String string1 = null; try { string1 = EntityUtils.toString(entity1); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(string1); JSONObject allIssues = new JSONObject(string1); JSONArray IssuesArray = allIssues.getJSONArray("issues"); // System.out.println(IssuesArray.length()); if (IssuesArray.length() == 0) { return issueIds; } for (int j = 0; j < IssuesArray.length(); j++) { JSONObject jobj = IssuesArray.getJSONObject(j); String issueId = jobj.getString("id"); issueIds[j] = issueId; } } return issueIds; }
From source file:com.thed.zapi.cloud.sample.FetchExecuteUpdate.java
public static String updateExecutions(String uriStr, ZFJCloudRestClient client, String accessKey, StringEntity executionJSON) throws URISyntaxException, JSONException, ParseException, IOException { URI uri = new URI(uriStr); int expirationInSec = 360; JwtGenerator jwtGenerator = client.getJwtGenerator(); String jwt = jwtGenerator.generateJWT("PUT", uri, expirationInSec); // System.out.println(uri.toString()); // System.out.println(jwt); HttpResponse response = null;/*from w ww .java 2 s .c o m*/ HttpClient restClient = new DefaultHttpClient(); HttpPut executeTest = new HttpPut(uri); executeTest.addHeader("Content-Type", "application/json"); executeTest.addHeader("Authorization", jwt); executeTest.addHeader("zapiAccessKey", accessKey); executeTest.setEntity(executionJSON); try { response = restClient.execute(executeTest); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int statusCode = response.getStatusLine().getStatusCode(); // System.out.println(statusCode); String executionStatus = "No Test Executed"; // System.out.println(response.toString()); HttpEntity entity = response.getEntity(); if (statusCode >= 200 && statusCode < 300) { String string = null; try { string = EntityUtils.toString(entity); JSONObject executionResponseObj = new JSONObject(string); JSONObject descriptionResponseObj = executionResponseObj.getJSONObject("execution"); JSONObject statusResponseObj = descriptionResponseObj.getJSONObject("status"); executionStatus = statusResponseObj.getString("description"); System.out.println(executionResponseObj.get("issueKey") + "--" + executionStatus); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { try { String string = null; string = EntityUtils.toString(entity); JSONObject executionResponseObj = new JSONObject(string); cycleId = executionResponseObj.getString("clientMessage"); // System.out.println(executionResponseObj.toString()); throw new ClientProtocolException("Unexpected response status: " + statusCode); } catch (ClientProtocolException e) { e.printStackTrace(); } } return executionStatus; }