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; }
/** * @param response * @param context * @throws HttpException * @throws IOException */ public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { final HttpEntity entity = response.getEntity(); if (null != entity) { final Header encoding = entity.getContentEncoding(); if (null != encoding) { for (HeaderElement codec : encoding.getElements()) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }
public void run() { HttpPost httpPost = new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp)); // httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); // HttpResponse response = null; // This is acting as keep alive. // while (isActive()) { try { Thread.sleep(KEEP_ALIVE_PERIOD); httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8)); response = null; response = httpclient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); if (status != RestStreamHanlder.SUCCESS_200) { logger.error( "Cant register to the remote client, retrying in:" + (KEEP_ALIVE_PERIOD / 1000) + " seconds."); structure = registerAndGetStructure(); } } catch (Exception e) { logger.warn(e.getMessage(), e); } finally { if (response != null) { try { response.getEntity().getContent().close(); } catch (Exception e) { logger.warn(e.getMessage(), e); } } } } }
private String sendBasic(HttpRequestBase request) throws HttpException { try { HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String body = ""; if (entity != null) { body = EntityUtils.toString(entity, UTF_8); if (entity.getContentType() == null) { body = new String(body.getBytes(ISO_8859_1), UTF_8); } } int code = response.getStatusLine().getStatusCode(); if (code < 200 || code >= 300) { throw new Exception(String.format(" code : '%s' , body : '%s'", code, body)); } return body; } catch (Exception ex) { throw new HttpException( "Fail to send " + request.getMethod() + " request to url " + request.getURI() + ", " + ex.getMessage(), ex); } finally { request.releaseConnection(); } }
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (HeaderElement h : codecs) { if (h.getName().equalsIgnoreCase("deflate")) { response.setEntity(new DeflateDecompressingEntity(response.getEntity())); return; } } } } }
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; }
public Either<IOException, InputStream> apply(HttpResponse resp) { try { return new Right<IOException, InputStream>(resp.getEntity().getContent()); } catch (IOException e) { return new Left<IOException, InputStream>(e); } }
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 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; } }
/** @return {@link InputStream} from a {@link HttpResponse} */ InputStream getStream(HttpResponse response) { try { return response.getEntity().getContent(); } catch (Exception e) { log.error("Error reading response. " + e.getMessage()); throw new CouchDbException(e); } }
/** * Parses error response. * * @param response parsed <tt>ErrorResponse</tt> * @return <tt>ErrorResponse</tt> parsed from HTTP content stream. * @throws IOException if any IO issues occur. * @throws ParseException if any issues with JSON parsing occur. */ private ErrorResponse readErrorResponse(HttpResponse response) throws IOException, ParseException { BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); jsonParser.parse(rd, errorJson); return errorJson.getResult(); }
YammerHttpResponse execute(ApiQuery query) { HttpUriRequest request = generateRequest(query); setHeader(request); try { HttpResponse httpResponse = this.httpClient.execute(request); return new YammerHttpResponse( httpResponse.getStatusLine().getStatusCode(), readEntityAsString(httpResponse.getEntity())); } catch (IOException e) { return new YammerHttpResponse(e); } }
public Result<InputStream> getInputStream(String endpoint) throws IOException { HttpClient cli = createClient(); HttpGet get = createGet(endpoint); HttpResponse res = cli.execute(get); Object result = null; if (res.getStatusLine().getStatusCode() == 200) result = res.getEntity().getContent(); else { RestResponse resp = new RestResponse(res); result = unmarshalPOJO(resp, InputStream.class); cli.getConnectionManager().shutdown(); } return new Result<InputStream>(result); }
@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; }
private String readResult(HttpResponse response) { HttpEntity entity = response.getEntity(); String result = ""; try { result = EntityUtils.toString(entity); } catch (IOException e) { AppLogger.e(e.getMessage()); ActivityUtils.showTips(R.string.timeout); } AppLogger.d(result); return result; }
public Either<IOException, String> apply(HttpResponse response) { BufferedReader reader = null; try { StringBuilder builder = new StringBuilder(); reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); while (true) { String read = reader.readLine(); if (read == null) break; builder.append(read); } return new Right<IOException, String>(builder.toString()); } catch (IOException e) { return new Left<IOException, String>(e); } }
public String getRequest(String url, String queryString) { String responseText = ""; try { httpGet.setURI(new URI(url + "?" + queryString)); httpGet.addHeader("Accept", "application/json"); HttpResponse response = httpClient.execute(httpGet); responseText = EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e) { } catch (IOException e) { } catch (URISyntaxException e1) { } return responseText; }
public String postRequest(String url, List<NameValuePair> entity) { String responseText = ""; try { httpPost.setURI(new URI(url)); httpPost.addHeader("Accept", "application/json"); httpPost.setEntity(new UrlEncodedFormEntity(entity)); HttpResponse response = httpClient.execute(httpPost); responseText = EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e) { } catch (IOException e) { } catch (URISyntaxException e1) { } return responseText; }
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(); }
protected String postRallyXML(String apiUrl, String requestXML) throws Exception { String responseXML = ""; DefaultHttpClient httpClient = new DefaultHttpClient(); Base64 base64 = new Base64(); String encodeString = new String(base64.encode((rallyApiHttpUsername + ":" + rallyApiHttpPassword).getBytes())); HttpPost httpPost = new HttpPost(apiUrl); httpPost.addHeader("Authorization", "Basic " + encodeString); httpPost.setEntity(new StringEntity(requestXML)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); responseXML = getEntityString(entity); return responseXML; }
/** * Validates a HTTP response; on error cases logs status and throws relevant exceptions. * * @param response The HTTP response. */ private void validate(HttpResponse response) throws IOException { int code = response.getStatusLine().getStatusCode(); if (code == 200 || code == 201 || code == 202) { // success (ok | created | accepted) return; } String msg = format("<< Status: %s (%s) ", code, response.getStatusLine().getReasonPhrase()); switch (code) { case HttpStatus.SC_NOT_FOUND: { log.info(msg); throw new NoDocumentException(msg); } case HttpStatus.SC_CONFLICT: { log.warn(msg); throw new DocumentConflictException(msg); } default: { // other errors: 400 | 401 | 500 etc. log.error(msg += EntityUtils.toString(response.getEntity())); throw new CouchDbException(msg); } } }
/** * Parses JSON string returned in HTTP response and converts it to <tt>Conference</tt> instance. * * @param conference <tt>Conference</tt> instance that contains the data returned by API endpoint. * @param response HTTP response returned by the API endpoint. * @return <tt>Conference</tt> instance that contains the data returned by API endpoint. * @throws IOException if any IO problems occur. * @throws ParseException if any problems with JSON parsing occur. */ private Conference readConferenceResponse(Conference conference, HttpResponse response) throws IOException, ParseException { BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); if (conference != null) { conferenceJson.setForUpdate(conference); } jsonParser.parse(rd, conferenceJson); if (conference == null) { conference = conferenceJson.getResult(); } logger.info("ID: " + conference.getId()); logger.info("PIN: " + conference.getPin()); logger.info("URL: " + conference.getUrl()); logger.info("SIP ID: " + conference.getSipId()); logger.info("START TIME: " + conference.getStartTime()); logger.info("DURATION: " + conference.getDuration()); return conference; }
public void tempRedirectInvoke( @Nonnull String tempEndpoint, @Nonnull String method, @Nonnull String account, @Nonnull String resource, @Nonnull String body) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace( "enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")"); } if (wire.isDebugEnabled()) { wire.debug( "POST --------------------------------------------------------> " + endpoint + account + resource); wire.debug(""); } try { HttpClient client = getClient(); String url = tempEndpoint + account + resource; HttpRequestBase httpMethod = getMethod(method, url); // If it is networking configuration services if (httpMethod instanceof HttpPut) { if (url.endsWith("/services/networking/media")) { httpMethod.addHeader("Content-Type", "text/plain"); } else { httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8"); } } else { httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8"); } // dmayne version is older for anything to do with images and for disk deletion if (url.indexOf("/services/images") > -1 || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) { httpMethod.addHeader("x-ms-version", "2012-08-01"); } else { httpMethod.addHeader("x-ms-version", "2012-03-01"); } if (strategy != null && strategy.getSendAsHeader()) { httpMethod.addHeader(strategy.getHeaderName(), strategy.getRequestId()); } if (wire.isDebugEnabled()) { wire.debug(httpMethod.getRequestLine().toString()); for (Header header : httpMethod.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } if (httpMethod instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) httpMethod; if (body != null) { try { entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } HttpResponse response; StatusLine status; try { response = client.execute(httpMethod); status = response.getStatusLine(); } catch (IOException e) { logger.error( "post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("post(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) { logger.error("post(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); 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()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { throw new CloudException( CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown"); } logger.error( "post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug( "POST --------------------------------------------------------> " + endpoint + account + resource); } } }
public DataField[] registerAndGetStructure() throws IOException, ClassNotFoundException { // Create the POST request HttpPost httpPost = new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp)); // Add the POST parameters httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8)); // httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); // Create local execution context HttpContext localContext = new BasicHttpContext(); // NotificationRegistry.getInstance().addNotification(uid, this); int tries = 0; AuthState authState = null; // while (tries < 2) { tries++; HttpResponse response = null; try { // Execute the POST request response = httpclient.execute(httpPost, localContext); // int sc = response.getStatusLine().getStatusCode(); // if (sc == HttpStatus.SC_OK) { logger.debug( new StringBuilder() .append("Wants to consume the structure packet from ") .append(initParams.getRemoteContactPoint()) .toString()); structure = (DataField[]) XSTREAM.fromXML(response.getEntity().getContent()); logger.debug("Connection established for: " + initParams.getRemoteContactPoint()); break; } else { if (sc == HttpStatus.SC_UNAUTHORIZED) authState = (AuthState) localContext.getAttribute( ClientContext.TARGET_AUTH_STATE); // Target host authentication required else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) authState = (AuthState) localContext.getAttribute( ClientContext.PROXY_AUTH_STATE); // Proxy authentication required else { logger.error( new StringBuilder() .append("Unexpected POST status code returned: ") .append(sc) .append("\nreason: ") .append(response.getStatusLine().getReasonPhrase()) .toString()); } if (authState != null) { if (initParams.getUsername() == null || (tries > 1 && initParams.getUsername() != null)) { logger.error( "A valid username/password required to connect to the remote host: " + initParams.getRemoteContactPoint()); } else { AuthScope authScope = authState.getAuthScope(); logger.warn( new StringBuilder() .append("Setting Credentials for host: ") .append(authScope.getHost()) .append(":") .append(authScope.getPort()) .toString()); Credentials creds = new UsernamePasswordCredentials( initParams.getUsername(), initParams.getPassword()); httpclient.getCredentialsProvider().setCredentials(authScope, creds); } } } } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. logger.warn("Aborting the HTTP POST request."); httpPost.abort(); throw ex; } finally { if (response != null && response.getEntity() != null) { response.getEntity().consumeContent(); } } } if (structure == null) throw new RuntimeException("Cannot connect to the remote host."); return structure; }
/** * Gets content type of response * * @param response request response * @return content type */ protected static ContentType getContentType(HttpResponse response) { return ContentType.getOrDefault(response.getEntity()); }
/** * Gets string body of response * * @param response request response * @return response body * @throws IOException */ protected static String getResponseBody(HttpResponse response) throws IOException { HttpEntity entity = response.getEntity(); return entity == null ? null : EntityUtils.toString(entity); }
/** 连接网络读取数据 */ @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 String post(@Nonnull String account, @Nonnull String resource, @Nonnull String body) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace( "enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")"); } if (wire.isDebugEnabled()) { wire.debug( "POST --------------------------------------------------------> " + endpoint + account + resource); wire.debug(""); } String requestId = null; try { HttpClient client = getClient(); String url = endpoint + account + resource; HttpPost post = new HttpPost(url); if (url.toLowerCase().contains("operations")) { post.addHeader("x-ms-version", "2014-02-01"); } else if (url.toLowerCase().contains("/deployments")) { post.addHeader("x-ms-version", "2014-05-01"); } else { post.addHeader("x-ms-version", "2012-03-01"); } if (strategy != null && strategy.getSendAsHeader()) { post.addHeader(strategy.getHeaderName(), strategy.getRequestId()); } // If it is networking configuration services if (url.endsWith("/services/networking/media")) { post.addHeader("Content-Type", "text/plain;charset=UTF-8"); } else { post.addHeader("Content-Type", "application/xml;charset=UTF-8"); } if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } if (body != null) { try { if (url.endsWith("/services/networking/media")) { post.setEntity(new StringEntity(body, "text/plain", "utf-8")); } else { post.setEntity(new StringEntity(body, "application/xml", "utf-8")); } } catch (UnsupportedEncodingException e) { throw new InternalException(e); } } HttpResponse response; StatusLine status; try { response = client.execute(post); status = response.getStatusLine(); } catch (IOException e) { logger.error( "post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("post(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); } for (Header h : headers) { if (h.getValue() != null) { if (wire.isDebugEnabled()) { wire.debug(h.getName() + ": " + h.getValue().trim()); } if (h.getName().equalsIgnoreCase("x-ms-request-id")) { requestId = h.getValue().trim(); } } else { if (wire.isDebugEnabled()) { wire.debug(h.getName() + ":"); } } } if (wire.isDebugEnabled()) { wire.debug(""); } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) { logger.error("post(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); 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()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { throw new CloudException( CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown"); } logger.error( "post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug( "POST --------------------------------------------------------> " + endpoint + account + resource); } } return requestId; }
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()); } }