protected String getRallyXML(String apiUrl) throws Exception { String responseXML = ""; DefaultHttpClient httpClient = new DefaultHttpClient(); Base64 base64 = new Base64(); String encodeString = new String(base64.encode((rallyApiHttpUsername + ":" + rallyApiHttpPassword).getBytes())); HttpGet httpGet = new HttpGet(apiUrl); httpGet.addHeader("Authorization", "Basic " + encodeString); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { InputStreamReader reader = new InputStreamReader(entity.getContent()); BufferedReader br = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } responseXML = sb.toString(); } log.debug("responseXML=" + responseXML); return responseXML; }
public static byte[] httpEntityToByteArray(final HttpEntity entity) throws IOException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); if (instream == null) { return new byte[] {}; } if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } ByteArrayBuffer buffer = new ByteArrayBuffer(i); try { byte[] tmp = new byte[4096]; int l; while ((l = instream.read(tmp)) != -1) { if (Thread.interrupted()) throw new InterruptedIOException("File download process was canceled"); buffer.append(tmp, 0, l); } } finally { instream.close(); } return buffer.toByteArray(); }
private boolean fetchApp(String url, String username, String password) throws JSONException { try { if (username == "null") { username = null; } if (password == "null") { password = null; } HttpResponse response = makeRequest(url, username, password); StatusLine sl = response.getStatusLine(); int code = sl.getStatusCode(); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); if (code != 200) { return false; } else { ZipInputStream data = new ZipInputStream(content); return saveAndVerify(data); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } }
public String readTwitterFeed() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http:'//twitter.com/users/show/vogella.json"); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 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(MainActivity2.class.toString(), "Failed to download file"); } } catch (ClientProtocolExpcetion e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); }
private String readEntityAsString(HttpEntity entity) throws IOException { if (entity == null) { throw new IOException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); if (instream == null) { return null; } try { if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IOException("HTTP entity too large"); } int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } if (entity.getContentEncoding() != null && entity.getContentEncoding().getValue().equals("gzip")) { instream = new GZIPInputStream(instream); } Reader reader = new InputStreamReader(instream, HTTP.UTF_8); CharArrayBuffer buffer = new CharArrayBuffer(i); char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toString(); } finally { instream.close(); } }
public String readResponse(HttpResponse response) { String output = ""; HttpEntity entity = response.getEntity(); try { trapException(response.getStatusLine().getStatusCode()); } catch (CrowdFlowerException e1) { e1.printStackTrace(); } InputStream instream; try { instream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); // do something useful with the response output = output + reader.readLine(); instream.close(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return output; }
@Override protected Void doInBackground(String... params) { // TODO Auto-generated method stub InputStream is = null; ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("username", _username.getText().toString())); nameValuePairs.add(new BasicNameValuePair("password", _password.getText().toString())); // http post try { HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 10000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 10000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost httppost = new HttpPost("http://trainingbuddy.comuv.com/login.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); conSuccess = true; } catch (Exception e) { e.printStackTrace(); this.progressDialog.dismiss(); } try { BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString().substring(0, 1); userDetails = sb.toString().substring(1); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return null; }
public String getEntityString(HttpEntity entity) throws Exception { StringBuilder sb = new StringBuilder(); if (entity != null) { InputStreamReader reader = new InputStreamReader(entity.getContent()); BufferedReader br = new BufferedReader(reader); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } } return sb.toString(); }
public static void main(String[] args) throws MalformedURLException, IOException { URLConnection con = new URL("http://localhost:8080/RobotControlServer/rest/control/hello").openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); HttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://localhost:8080/RobotControlServer/rest/control/photo"); byte[] bytes = {0x01b}; httpPost.setEntity(new ByteArrayEntity(bytes)); HttpResponse response = client.execute(httpPost); HttpEntity entity = response.getEntity(); InputStream inStream = entity.getContent(); // Apache IOUtils makes this pretty easy :) System.out.println(IOUtils.toString(inStream)); inStream.close(); }
@Override public InputStream getContent() throws IOException, IllegalStateException { return delegate.getContent(); }
/** 连接网络读取数据 */ @Override protected <T> void connectWithRetries(AbstractRequest<T> request, InternalResponse response) throws HttpClientException, HttpNetException, HttpServerException { // if(true) { // throw new HttpNetException(NetException.NetworkDisabled); // } // 1. create apache request final HttpUriRequest apacheRequest = createApacheRequest(request); // 2. update http header if (request.getHeaders() != null) { Set<Entry<String, String>> set = request.getHeaders().entrySet(); for (Entry<String, String> en : set) { apacheRequest.setHeader(new BasicHeader(en.getKey(), en.getValue())); } } // 3. try to connect HttpListener<T> listener = request.getHttpListener(); StatisticsListener statistic = response.getStatistics(); int times = 0, maxRetryTimes = request.getMaxRetryTimes(), maxRedirectTimes = request.getMaxRedirectTimes(); boolean retry = true; IOException cause = null; while (retry) { try { cause = null; retry = false; if (request.isCancelledOrInterrupted()) { return; } if (statistic != null) { statistic.onPreConnect(request); } HttpResponse ares = mHttpClient.execute(apacheRequest); if (statistic != null) { statistic.onAfterConnect(request); } // status StatusLine status = ares.getStatusLine(); HttpStatus httpStatus = new HttpStatus(status.getStatusCode(), status.getReasonPhrase()); response.setHttpStatus(httpStatus); // header Header[] headers = ares.getAllHeaders(); if (headers != null) { com.litesuits.http.data.NameValuePair hs[] = new com.litesuits.http.data.NameValuePair[headers.length]; for (int i = 0; i < headers.length; i++) { String name = headers[i].getName(); String value = headers[i].getValue(); if ("Content-Length".equalsIgnoreCase(name)) { response.setContentLength(Long.parseLong(value)); } hs[i] = new com.litesuits.http.data.NameValuePair(name, value); } response.setHeaders(hs); } // data body if (status.getStatusCode() <= 299 || status.getStatusCode() == 600) { // 成功 HttpEntity entity = ares.getEntity(); if (entity != null) { // charset String charSet = getCharsetFromEntity(entity, request.getCharSet()); response.setCharSet(charSet); // is cancelled ? if (request.isCancelledOrInterrupted()) { return; } // length long len = response.getContentLength(); DataParser<T> parser = request.getDataParser(); if (statistic != null) { statistic.onPreRead(request); } parser.readFromNetStream(entity.getContent(), len, charSet); if (statistic != null) { statistic.onAfterRead(request); } response.setReadedLength(parser.getReadedLength()); endEntityViaReflection(entity); } return; } else if (status.getStatusCode() <= 399) { // redirect if (response.getRedirectTimes() < maxRedirectTimes) { // get the location header to find out where to redirect to Header locationHeader = ares.getFirstHeader(Consts.REDIRECT_LOCATION); if (locationHeader != null) { String location = locationHeader.getValue(); if (location != null && location.length() > 0) { if (!location.toLowerCase().startsWith("http")) { URI uri = new URI(request.getFullUri()); URI redirect = new URI(uri.getScheme(), uri.getHost(), location, null); location = redirect.toString(); } response.setRedirectTimes(response.getRedirectTimes() + 1); request.setUri(location); if (HttpLog.isPrint) { HttpLog.i(TAG, "Redirect to : " + location); } if (listener != null) { listener.notifyCallRedirect( request, maxRedirectTimes, response.getRedirectTimes()); } connectWithRetries(request, response); return; } } throw new HttpServerException(httpStatus); } else { throw new HttpServerException(ServerException.RedirectTooMuch); } } else if (status.getStatusCode() <= 499) { // 客户端被拒 throw new HttpServerException(httpStatus); } else if (status.getStatusCode() < 599) { // 服务器有误 throw new HttpServerException(httpStatus); } } catch (IOException e) { cause = e; } catch (NullPointerException e) { // bug in HttpClient 4.0.x, see http://code.google.com/p/android/issues/detail?id=5255 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { cause = new IOException(e.getMessage()); } else { cause = new IOException(e); } } catch (URISyntaxException e) { throw new HttpClientException(e); } catch (IllegalStateException e) { // for apache http client. if url is illegal, it usually raises an exception as // "IllegalStateException: // Scheme 'xxx' not registered." throw new HttpClientException(e); } catch (SecurityException e) { throw new HttpClientException(e, ClientException.PermissionDenied); } catch (RuntimeException e) { throw new HttpClientException(e); } if (cause != null) { try { if (request.isCancelledOrInterrupted()) { return; } times++; retry = retryHandler.retryRequest( cause, times, maxRetryTimes, mHttpContext, config.getContext()); } catch (InterruptedException e) { e.printStackTrace(); return; } if (retry) { response.setRetryTimes(times); if (HttpLog.isPrint) { HttpLog.i(TAG, "LiteHttp retry request: " + request.getUri()); } if (listener != null) { listener.notifyCallRetry(request, maxRetryTimes, times); } } } } if (cause != null) { throw new HttpNetException(cause); } }
@Override protected String doInBackground(Void... voidstr) { JSONObject jsonObject = new JSONObject(); try { jsonObject.accumulate("firstName", firstName); jsonObject.accumulate("lastName", lastName); jsonObject.accumulate("phoneNumber", phoneNumber); jsonObject.accumulate("address", addr); // Add a nested JSONObject (e.g. for header information) JSONObject header = new JSONObject(); header.put("deviceType", "Android"); // Device type header.put("deviceVersion", "2.0"); // Device OS version header.put("language", "es-es"); // Language of the Android client jsonObject.put("header", header); // Output the JSON object we're sending to Logcat: URL = "http://162.243.114.166/cgi-bin/Database_scripts/Registration_script.py"; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(URL); System.out.println("printing json object : " + jsonObject); String se; se = jsonObject.toString(); System.out.println("printing se : " + se); // Set HTTP parameters httpPostRequest.setEntity(se); System.out.println("printing req : " + httpPostRequest.getEntity().getContent().toString()); httpPostRequest.setHeader("Accept", "application/json"); httpPostRequest.setHeader("Content-type", "application/json"); // httpPostRequest.setHeader("Content-length", IntegejsonObjSend.toString().length()); // httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you // would like to use gzip compression InputStream inp = httpPostRequest.getEntity().getContent(); String req = convertStreamToString(inp); System.out.println("printing entities : " + req); System.out.println("printing http request message : message is :" + httpPostRequest); HttpResponse response = null; try { response = (HttpResponse) httpclient.execute(httpPostRequest); } catch (Exception ex) { System.out.println("printing error :" + ex); } InputStream is = response.getEntity().getContent(); String res = convertStreamToString(is); System.out.println("printing Response is :" + res); System.out.println("printing response code : " + response.getStatusLine().getStatusCode()); // Get hold of the response entity (-> the data) HttpEntity entity = response.getEntity(); String serverresp = entity.toString(); System.out.println( "printing server response, entity length : " + entity.getContentLength()); System.out.println("printing server response : " + serverresp); if (entity != null) { // Read the content stream InputStream instream = entity.getContent(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } System.out.println("Debug point : 1.3"); // convert content stream to a String String resultString = convertStreamToString(instream); instream.close(); resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]" // Transform the String into a JSONObject JSONObject jsonObjRecv = new JSONObject(resultString); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>"); System.out.println("Debug point : 1.4"); return jsonObjRecv; } // return serverresp; try { // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("q", se)); httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs)); System.out.println("printing http params: " + httpPostRequest.getParams().toString()); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httpPostRequest); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } } catch (Exception e) { System.out.println("Debug point : 1.4(a)"); // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } return null; }
public @Nullable InputStream getAsStream(@Nonnull String account, @Nonnull URI uri) throws CloudException, InternalException { logger.trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + uri + ")"); wire.debug("--------------------------------------------------------> " + uri.toASCIIString()); try { HttpClient client = getClient(); HttpUriRequest get = new HttpGet(uri); if (uri.toString().indexOf("/services/images") > -1) { get.addHeader("x-ms-version", "2012-08-01"); } else if (uri.toString().contains("/services/vmimages")) { get.addHeader("x-ms-version", "2014-05-01"); } else { get.addHeader("x-ms-version", "2012-03-01"); } if (strategy != null && strategy.getSendAsHeader()) { get.addHeader(strategy.getHeaderName(), strategy.getRequestId()); } wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } HttpResponse response; StatusLine status; try { response = client.execute(get); status = response.getStatusLine(); } catch (IOException e) { logger.error( "get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } logger.debug("get(): HTTP Status " + status); Header[] headers = response.getAllHeaders(); wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) { return null; } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { logger.error("get(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String body; if (entity == null) { throw new AzureException( CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException( CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } wire.debug(body); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { return null; } logger.error( "get(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } else { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } InputStream input; try { input = entity.getContent(); } catch (IOException e) { logger.error( "get(): Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } wire.debug("---> Binary Data <---"); return input; } } finally { logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()"); wire.debug( "--------------------------------------------------------> " + uri.toASCIIString()); } }