List of usage examples for org.apache.http.client HttpClient execute
HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException;
From source file:org.deviceconnect.message.intent.util.IntentAuthProcessor.java
/** * ????JSON?.//w ww . jav a 2s .com * * @param client * @param request * @return ????null? * @throws IOException ??????? */ private static JSONObject execute(final HttpClient client, final HttpUriRequest request) throws IOException { HttpResponse response = client.execute(request); String entity = EntityUtils.toString(response.getEntity(), "UTF-8"); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { return null; } JSONObject json; try { json = new JSONObject(entity); } catch (JSONException e) { json = null; } return json; }
From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java
public static String getHtml(String url) throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(content)); StringBuffer responseBuffer = new StringBuffer(); String line = ""; while ((line = in.readLine()) != null) { responseBuffer.append(line);/*from w w w . j a va 2 s . c o m*/ } return responseBuffer.toString(); }
From source file:com.mysoft.b2b.event.util.HttpUtil.java
/** * http???/*from w w w. j ava 2 s.c o m*/ * @param uri ? * @param body ? */ public static Integer send(String uri, String body) { if (StringUtils.isEmpty(uri) || StringUtils.isEmpty(body)) return null; HttpClient client = new DefaultHttpClient(); try { HttpPost post = new HttpPost(uri + "/dealEvent.do"); post.addHeader("Content-Type", "application/json;charset=UTF-8"); HttpEntity entity = new StringEntity(body); post.setEntity(entity); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); return code; } catch (Exception e) { logger.error("http???" + e); } return null; }
From source file:org.wso2.greg.plugin.Utils.java
private static String getResourceContent(String swaggerDocLink) throws IOException { HttpGet request = new HttpGet(swaggerDocLink); HttpClient client = getHttpClient(); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, ResourceConstants.UTF_8); return responseString; }
From source file:com.fallenangelsguild.eltime.WebHelper.java
/** * Pull the raw text content of the given URL. This call blocks until the * operation has completed, and is synchronized because it uses a shared * buffer {@link #sBuffer}./*from w w w. j a va 2 s .c o m*/ * * @param url The exact URL to request. * @return The raw content returned by the server. * @throws ApiException If any connection or server error occurs. */ protected static synchronized String getUrlContent(String url) throws ApiException { if (c == null) { throw new ApiException("Must initialize() first"); } // Create client and set our specific user-agent string HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); request.setHeader("User-Agent", sUserAgent); try { HttpResponse response = client.execute(request); // Check if server response is valid StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HTTP_STATUS_OK) { throw new ApiException("Invalid response from server: " + status.toString()); } // Pull content stream from response HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } // Return result from buffered stream return new String(content.toByteArray()); } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } }
From source file:com.fhc25.percepcion.osiris.mapviewer.common.restutils.RestClientStream.java
private static void serverConnection(HttpClient client, HttpUriRequest request, RestListenerStream listener) { try {//from w w w .j a v a 2 s.co m HttpResponse httpResponse = client.execute(request); mResponseCode = httpResponse.getStatusLine().getStatusCode(); mMessage = httpResponse.getStatusLine().getReasonPhrase(); HttpEntity entity = httpResponse.getEntity(); if (mResponseCode >= 200 && mResponseCode <= 299) { InputStream isResponse = null; if (entity != null) { isResponse = entity.getContent(); } listener.onComplete(isResponse); } else { String errorText = convertStreamToString(entity.getContent()); Lgr.e(TAG, errorText); RestError error = null; try { error = new RestError(errorText); } catch (JSONException je) { error = new RestError(-1, 3, "Malformed response"); } listener.onError(error); } Lgr.v(TAG, "ResponseCode: " + mResponseCode); } catch (ConnectTimeoutException e) { //e.printStackTrace(); //listener.onError(new KError(508, 0, e.getMessage())); listener.onConnectionFailed(); } catch (SocketTimeoutException e) { //e.printStackTrace(); //listener.onError(new KError(508, 0, e.getMessage())); listener.onConnectionFailed(); } catch (UnknownHostException e) { Lgr.e(TAG, e.getMessage()); listener.onConnectionFailed(); } catch (IOException e) { Lgr.e(TAG, e.getMessage()); listener.onConnectionFailed(); } catch (Exception e) { e.printStackTrace(); listener.onError(new RestError(-1, 0, e.getMessage())); } }
From source file:eu.musesproject.windowsclient.contextmonitoring.sensors.RESTController.java
public static Map<String, String> requestSensorInfo(String sensorType, String[] params) throws IOException { HttpClient client = new DefaultHttpClient(); // join params String paramsStr = "/"; for (String param : params) { paramsStr += param + "/"; }/*from ww w. ja v a2 s . co m*/ HttpGet request = new HttpGet("http://localhost:9000/api/" + sensorType + paramsStr); HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String responseData = ""; Gson gson = new Gson(); //ToDo:check for readLine function responseData = rd.readLine(); return gson.fromJson(responseData, new HashMap<String, String>().getClass()); }
From source file:org.wso2.security.tools.advisorytool.utils.Util.java
/** * This method is used to initiate an HTTP connection and retrieve the response. * * @param url/*from w w w . ja v a 2 s . co m*/ * @param * @return */ public static StringBuilder httpConnection(String url, List<Header> headerList) throws AdvisoryToolException { HttpResponse response = null; StringBuilder result = new StringBuilder(); String line = ""; try { HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); for (Header header : headerList) { request.addHeader(header.getHeaderName(), header.getHeaderValue()); } response = client.execute(request); } catch (IOException e) { throw new AdvisoryToolException("Connection to the URL " + url + " failed", e); } try (BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8"))) { while ((line = rd.readLine()) != null) { result.append(line); } } catch (IOException e) { throw new AdvisoryToolException("Error occured while reading the response from " + url, e); } return result; }
From source file:cn.newgxu.android.bbs.util.NewgxuUtils.java
public static final String get(String url, String charset) { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); get.setHeader("Accept", "application/json"); HttpResponse response = null;//from ww w. j a v a 2 s . c o m HttpEntity entity = null; Scanner scanner = null; try { response = client.execute(get); entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream in = entity.getContent(); scanner = new Scanner(in, charset == null ? "utf-8" : charset).useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : null; } } catch (ClientProtocolException e) { Log.wtf(TAG, e); } catch (IOException e) { Log.wtf(TAG, e); } finally { try { if (entity != null) { entity.consumeContent(); } } catch (IOException e) { Log.wtf(TAG, e); } } return null; }
From source file:com.github.commonclasses.network.DownloadUtils.java
public static long download(String urlStr, File dest, boolean append, DownloadListener downloadListener) throws Exception { int downloadProgress = 0; long remoteSize = 0; int currentSize = 0; long totalSize = -1; if (!append && dest.exists() && dest.isFile()) { dest.delete();/* w ww . j a v a 2s . c o m*/ } if (append && dest.exists() && dest.exists()) { FileInputStream fis = null; try { fis = new FileInputStream(dest); currentSize = fis.available(); } catch (IOException e) { throw e; } finally { if (fis != null) { fis.close(); } } } HttpGet request = new HttpGet(urlStr); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); if (currentSize > 0) { request.addHeader("RANGE", "bytes=" + currentSize + "-"); } HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT); HttpConnectionParams.setSoTimeout(params, DATA_TIMEOUT); HttpClient httpClient = new DefaultHttpClient(params); InputStream is = null; FileOutputStream os = null; try { HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { is = response.getEntity().getContent(); remoteSize = response.getEntity().getContentLength(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { is = new GZIPInputStream(is); } os = new FileOutputStream(dest, append); byte buffer[] = new byte[DATA_BUFFER]; int readSize = 0; while ((readSize = is.read(buffer)) > 0) { os.write(buffer, 0, readSize); os.flush(); totalSize += readSize; if (downloadListener != null) { downloadProgress = (int) (totalSize * 100 / remoteSize); downloadListener.downloading(downloadProgress); } } if (totalSize < 0) { totalSize = 0; } } } catch (Exception e) { if (downloadListener != null) { downloadListener.exception(e); } e.printStackTrace(); } finally { if (os != null) { os.close(); } if (is != null) { is.close(); } } if (totalSize < 0) { throw new Exception("Download file fail: " + urlStr); } if (downloadListener != null) { downloadListener.downloaded(dest); } return totalSize; }