Java Code Examples for org.apache.http.HttpResponse
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project Axon-trader, under directory /external-listeners/src/main/java/org/axonframework/samples/trader/listener/.
Source file: OrderbookExternalListener.java

private void doHandle(TradeExecutedEvent event) throws IOException { String jsonObjectAsString=createJsonInString(event); HttpPost post=new HttpPost(remoteServerUri); post.setEntity(new StringEntity(jsonObjectAsString)); post.addHeader("Content-Type","application/json"); HttpClient client=new DefaultHttpClient(); HttpResponse response=client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { Writer writer=new StringWriter(); IOUtils.copy(response.getEntity().getContent(),writer); logger.warn("Error while sending event to external system: {}",writer.toString()); } }
Example 2
From project 2Degrees-Toolbox, under directory /Toolbox/src/biz/shadowservices/DegreesToolbox/.
Source file: HttpGetter.java

public String execute() throws ClientProtocolException, IOException { if (response == null) { HttpClient httpClient=HttpClientSingleton.getInstance(); HttpResponse serverresponse=null; serverresponse=httpClient.execute(httpget); HttpEntity entity=serverresponse.getEntity(); StringWriter writer=new StringWriter(); IOUtils.copy(entity.getContent(),writer); response=writer.toString(); } return response; }
Example 3
From project android_packages_apps_Exchange, under directory /src/com/android/exchange/.
Source file: EasResponse.java

public static EasResponse fromHttpRequest(EmailClientConnectionManager connManager,HttpClient client,HttpUriRequest request) throws IOException { long reqTime=System.currentTimeMillis(); HttpResponse response=client.execute(request); EasResponse result=new EasResponse(response); if (isAuthError(response.getStatusLine().getStatusCode()) && connManager.hasDetectedUnsatisfiedCertReq(reqTime)) { result.mClientCertRequested=true; result.mClosed=true; } return result; }
Example 4
From project artifactory-plugin, under directory /src/main/java/org/jfrog/hudson/release/.
Source file: PromoteBuildAction.java

private void handlePluginPromotion(TaskListener listener,ArtifactoryBuildInfoClient client) throws IOException { String buildName=ExtractorUtils.sanitizeBuildName(build.getParent().getFullName()); String buildNumber=build.getNumber() + ""; HttpResponse pluginPromotionResponse=client.executePromotionUserPlugin(promotionPlugin.getPluginName(),buildName,buildNumber,promotionPlugin.getParamMap()); if (checkSuccess(pluginPromotionResponse,false,false,listener)) { listener.getLogger().println("Promotion completed successfully!"); } }
Example 5
From project Amantech, under directory /Android/CloudAppStudioAndroid/src/com/cloudappstudio/utility/.
Source file: CloudOAuth.java

public String getContent(String apiUrl) throws IllegalStateException, IOException { DefaultHttpClient httpClient=new DefaultHttpClient(); BasicHttpParams params=new BasicHttpParams(); HttpClientParams.setRedirecting(params,false); httpClient.setParams(params); HttpGet httpget=new HttpGet(apiUrl + "?userInfoOAuth=" + id.getToken()); HttpResponse response=httpClient.execute(httpget); Log.d("debug","" + response.getStatusLine().getStatusCode()); Log.d("debug","" + response.getStatusLine()); return this.readTextFromHttpResponse(response); }
Example 6
From project android-api_1, under directory /android-lib/src/com/catchnotes/api/.
Source file: CatchAPI.java

/** * Deletes a media item. * @param noteId The note containing the media you want to remove. * @param mediaId ID of the media. * @return RESULT_OK on success. */ public int deleteMedia(String noteId,String mediaId){ int returnCode=RESULT_ERROR; HttpResponse response=performDELETE(API_ENDPOINT_MEDIA + '/' + noteId+ '/'+ mediaId,null); if (response != null) { if (isResponseOK(response)) { returnCode=RESULT_OK; } else if (isResponseUnauthorized(response)) { returnCode=RESULT_UNAUTHORIZED; } consumeResponse(response); } return returnCode; }
Example 7
From project android-async-http, under directory /src/com/loopj/android/http/.
Source file: AsyncHttpRequest.java

private void makeRequest() throws IOException { if (!Thread.currentThread().isInterrupted()) { HttpResponse response=client.execute(request,context); if (!Thread.currentThread().isInterrupted()) { if (responseHandler != null) { responseHandler.sendResponseMessage(response); } } else { } } }
Example 8
From project android-client, under directory /xwiki-android-rest/src/org/xwiki/android/rest/.
Source file: HttpConnector.java

/** * @param uri * @param res The resource to be posted to server. Ex {@link Comment} * @param retType The type of Resource to be extracted from the response to post request * @return * @throws RestConnectionException * @throws RestException */ public <T extends Resource>T postForResource(String uri,Resource res,Class<T> retType) throws RestConnectionException, RestException { String content=toXmlString(res); HttpResponse response=post(uri,content); if (retType != null) { return buildResource(retType,response.getEntity()); } else { return null; } }
Example 9
From project bbb-java, under directory /src/main/java/org/mconf/bbb/api/.
Source file: JoinServiceBase.java

protected static String getUrl(HttpClient client,String url) throws IOException, ClientProtocolException { HttpGet method=new HttpGet(url); HttpResponse httpResponse=client.execute(method); if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) log.debug("HTTP GET {} return {}",url,httpResponse.getStatusLine().getStatusCode()); return EntityUtils.toString(httpResponse.getEntity()).trim(); }
Example 10
From project beanstalker, under directory /cloudfront-maven-plugin/src/main/java/br/com/ingenieux/mojo/cloudfront/.
Source file: UpdateDistributionMojo.java

protected String getETag(Distribution d,String path) throws IOException, ClientProtocolException { if (!isBlank(d.s3Bucket)) return s3Client.getObjectMetadata(d.s3Bucket,path).getETag(); String assetUrl=String.format("http://%s/%s",d.domainName,path); getLog().info("Checking for eTag on " + assetUrl); HttpResponse result=httpClient.execute(new HttpHead(assetUrl)); getLog().info("Status Code:" + result.getStatusLine().getStatusCode()); if (result.containsHeader("ETag")) { String eTag=strip(result.getFirstHeader("ETag").getValue(),"\""); getLog().info("ETag is " + eTag); return eTag; } return ""; }
Example 11
From project Absolute-Android-RSS, under directory /src/com/AA/Other/.
Source file: RSSParse.java

/** * Get the XML document for the RSS feed * @return the XML Document for the feed on success, on error returns null */ private static Document getDocument(){ Document doc=null; try { DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); DefaultHttpClient client=new DefaultHttpClient(); HttpGet request=new HttpGet(URI); HttpResponse response=client.execute(request); doc=builder.parse(response.getEntity().getContent()); } catch ( java.io.IOException e) { return null; } catch ( SAXException e) { Log.e("AARSS","Parse Exception in RSS feed",e); return null; } catch ( Exception e) { return null; } return doc; }
Example 12
From project accesointeligente, under directory /src/org/accesointeligente/server/robots/.
Source file: SIAC.java

@Override public void login() throws Exception { if (characterEncoding == null) { detectCharacterEncoding(); } List<NameValuePair> formParams; HttpPost post; HttpResponse response; TagNode document, hiddenUser; try { formParams=new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair("usuario",username)); formParams.add(new BasicNameValuePair("clave",password)); formParams.add(new BasicNameValuePair("accion","login")); post=new HttpPost(baseUrl + "/formulario.gov"); post.addHeader("Referer",baseUrl + "/formulario.gov?accion=ingresa"); post.setEntity(new UrlEncodedFormEntity(formParams,characterEncoding)); response=client.execute(post); document=cleaner.clean(new InputStreamReader(response.getEntity().getContent(),characterEncoding)); hiddenUser=document.findElementByAttValue("id","user",true,true); if (hiddenUser == null || !hiddenUser.hasAttribute("value") || hiddenUser.getAttributeByName("value").equals("0")) { throw new RobotException("Invalid user id field"); } userId=hiddenUser.getAttributeByName("value"); loggedIn=true; } catch ( Exception ex) { logger.error(ex.getMessage(),ex); throw ex; } }
Example 13
From project accounted4, under directory /accounted4/stock-quote/stock-quote-yahoo/src/main/java/com/accounted4/stockquote/yahoo/.
Source file: YahooQuoteService.java

@Override public List<HashMap<QuoteAttribute,String>> executeQuery(List<String> securityList,List<QuoteAttribute> quoteAttributes){ String tickerList=securityListToString(securityList); String attributeList=attributeListToString(quoteAttributes); HttpClient httpclient=new DefaultHttpClient(); String urlString=BASE_URL + "?" + "s="+ tickerList+ "&"+ "f="+ attributeList; System.out.println("Query url: " + urlString); HttpGet httpGet=new HttpGet(urlString); try { HttpResponse response=httpclient.execute(httpGet); HttpEntity entity=response.getEntity(); if (entity != null) { String stringResponse=EntityUtils.toString(entity); return processResponse(stringResponse,quoteAttributes); } } catch ( IOException ex) { System.out.println("Error " + ex); } List<HashMap<QuoteAttribute,String>> result=new ArrayList<>(); return result; }
Example 14
From project adg-android, under directory /src/com/analysedesgeeks/android/service/impl/.
Source file: DownloadServiceImpl.java

@Override public boolean downloadFeed(){ boolean downloadSuccess=false; if (connectionService.isConnected()) { InputStream inputStream=null; try { final HttpGet httpget=new HttpGet(new URI(Const.FEED_URL)); final HttpResponse response=new DefaultHttpClient().execute(httpget); final StatusLine status=response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { Ln.e("Erreur lors du t??hargement:%s,%s",status.getStatusCode(),status.getReasonPhrase()); } else { final HttpEntity entity=response.getEntity(); inputStream=entity.getContent(); final ByteArrayOutputStream content=new ByteArrayOutputStream(); int readBytes=0; final byte[] sBuffer=new byte[512]; while ((readBytes=inputStream.read(sBuffer)) != -1) { content.write(sBuffer,0,readBytes); } final String dataAsString=new String(content.toByteArray()); final List<FeedItem> syndFeed=rssService.parseRss(dataAsString); if (syndFeed != null) { databaseService.save(dataAsString); downloadSuccess=true; } } } catch ( final Throwable t) { Ln.e(t); } finally { closeQuietly(inputStream); } } return downloadSuccess; }
Example 15
From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/http/.
Source file: HttpBuilder.java

private <T>HttpResult<T> doRequest(HttpUriRequest request,Type target){ DefaultHttpClient client=new DefaultHttpClient(); HttpResult<T> result=new HttpResult<T>(); Reader reader=null; InputStream content=null; String fullJson=null; try { client.addRequestInterceptor(preemptiveAuth(),0); HttpResponse response=client.execute(request); content=response.getEntity().getContent(); reader=new InputStreamReader(content); if (Constants.isDevMode()) { List<String> strings=CharStreams.readLines(reader); fullJson=Joiner.on("\n").join(strings); reader=new StringReader(fullJson); } T output=gson.fromJson(reader,target); result.setContent(output); result.setStatus(response.getStatusLine().getStatusCode() < 300 ? Status.SUCCESS : Status.FAILURE); } catch ( Exception e) { Log.e(Constants.TAG,"Http request failed",e); result.setStatus(Status.ERROR); return result; } finally { closeQuietly(content); closeQuietly(reader); client.getConnectionManager().shutdown(); } return result; }
Example 16
From project ajah, under directory /ajah-http/src/main/java/com/ajah/http/.
Source file: Http.java

private static HttpEntity internalGet(final URI uri) throws IOException, ClientProtocolException, NotFoundException, UnexpectedResponseCode { final HttpClient httpclient=new DefaultHttpClient(); final HttpGet httpget=new HttpGet(uri); final HttpResponse response=httpclient.execute(httpget); if (response.getStatusLine().getStatusCode() == 200) { final HttpEntity entity=response.getEntity(); return entity; } else if (response.getStatusLine().getStatusCode() == 404) { throw new NotFoundException(response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase()); } else { throw new UnexpectedResponseCode(response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase()); } }
Example 17
From project amber, under directory /oauth-2.0/httpclient4/src/main/java/org/apache/amber/oauth2/httpclient4/.
Source file: HttpClient4.java

public <T extends OAuthClientResponse>T execute(OAuthClientRequest request,Map<String,String> headers,String requestMethod,Class<T> responseClass) throws OAuthSystemException, OAuthProblemException { try { URI location=new URI(request.getLocationUri()); HttpRequestBase req=null; String responseBody=""; if (!OAuthUtils.isEmpty(requestMethod) && OAuth.HttpMethod.POST.equals(requestMethod)) { req=new HttpPost(location); HttpEntity entity=new StringEntity(request.getBody()); ((HttpPost)req).setEntity(entity); } else { req=new HttpGet(location); } if (headers != null && !headers.isEmpty()) { for ( Map.Entry<String,String> header : headers.entrySet()) { req.setHeader(header.getKey(),header.getValue()); } } HttpResponse response=client.execute(req); Header contentTypeHeader=null; HttpEntity entity=response.getEntity(); if (entity != null) { responseBody=EntityUtils.toString(entity); contentTypeHeader=entity.getContentType(); } String contentType=null; if (contentTypeHeader != null) { contentType=contentTypeHeader.toString(); } return OAuthClientResponseFactory.createCustomResponse(responseBody,contentType,response.getStatusLine().getStatusCode(),responseClass); } catch ( Exception e) { throw new OAuthSystemException(e); } }
Example 18
From project and-bible, under directory /jsword-tweaks/src/main/java/jsword/org/crosswire/common/util/.
Source file: WebResource.java

/** * Determine the size of this WebResource. <p> Note that the http client may read the entire file to determine this. </p> * @return the size of the file */ public int getSize(){ HttpRequestBase method=new HttpHead(uri); HttpResponse response=null; try { response=client.execute(method); StatusLine statusLine=response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { return getHeaderAsInt(response,"Content-Length"); } String reason=response.getStatusLine().getReasonPhrase(); Reporter.informUser(this,JSMsg.gettext("Unable to find: {0}",reason + ':' + uri.getPath())); } catch ( IOException e) { return 0; } return 0; }
Example 19
From project android-bankdroid, under directory /src/com/liato/bankdroid/banking/banks/.
Source file: Chalmrest.java

@Override public void update() throws BankException, LoginException, BankChoiceException { super.update(); if (username == null || username.length() == 0) throw new LoginException(res.getText(R.string.invalid_username_password).toString()); try { String cardNr=username; HttpClient httpclient=new DefaultHttpClient(); HttpGet httpget=new HttpGet("http://kortladdning.chalmerskonferens.se/bgw.aspx?type=getCardAndArticles&card=" + cardNr); HttpResponse response=httpclient.execute(httpget); HttpEntity entity=response.getEntity(); if (entity == null) throw new BankException("Couldn't connect!"); String s1=EntityUtils.toString(entity); Pattern pattern=Pattern.compile("<ExtendedInfo Name=\"Kortvarde\" Type=\"System.Double\" >(.*?)</ExtendedInfo>"); Matcher matcher=pattern.matcher(s1); if (!matcher.find()) throw new BankException("Couldn't parse value!"); String value=matcher.group(1); StringBuilder sb=new StringBuilder(); int last=0; Matcher match=Pattern.compile("_x([0-9A-Fa-f]{4})_").matcher(value); while (match.find()) { sb.append(value.substring(last,Math.max(match.start() - 1,0))); int i=Integer.parseInt(match.group(1),16); sb.append((char)i); last=match.end(); } sb.append(value.substring(last)); value=sb.toString(); matcher=Pattern.compile("<CardInfo id=\"" + cardNr + "\" Name=\"(.*?)\"").matcher(s1); if (!matcher.find()) throw new BankException("Coldn't parse name!"); String name=matcher.group(1); accounts.add(new Account(name,BigDecimal.valueOf(Double.parseDouble(value)),"1")); } catch ( Exception e) { throw new BankException(e.getMessage()); } finally { super.updateComplete(); } }
Example 20
From project android-rackspacecloud, under directory /main/java/net/elasticgrid/rackspace/common/.
Source file: RackspaceConnection.java

/** * Authenticate on Rackspace API. Tokens are only valid for 24 hours, so client code should expect token to expire and renew them if needed. * @return the auth token, valid for 24 hours * @throws RackspaceException if the credentials are invalid * @throws IOException if there is a network issue */ public String authenticate() throws RackspaceException, IOException { logger.info("Authenticating to Rackspace API..."); HttpGet request=new HttpGet(API_AUTH_URL); request.addHeader("X-Auth-User",username); request.addHeader("X-Auth-Key",apiKey); HttpResponse response=getHttpClient().execute(request); int statusCode=response.getStatusLine().getStatusCode(); switch (statusCode) { case 204: if (response.getFirstHeader("X-Server-Management-Url") != null) serverManagementURL=response.getFirstHeader("X-Server-Management-Url").getValue(); if (response.getFirstHeader("X-Storage-Url") != null) storageURL=response.getFirstHeader("X-Storage-Url").getValue(); if (response.getFirstHeader("X-CDN-Management-Url") != null) cdnManagementURL=response.getFirstHeader("X-CDN-Management-Url").getValue(); authToken=response.getFirstHeader("X-Auth-Token").getValue(); authenticated=true; return authToken; case 401: throw new RackspaceException("Invalid credentials: " + response.getStatusLine().getReasonPhrase()); default : throw new RackspaceException("Unexpected HTTP response"); } }
Example 21
From project android-rss, under directory /src/main/java/org/mcsoxford/rss/.
Source file: RSSReader.java

/** * Send HTTP GET request and parse the XML response to construct an in-memory representation of an RSS 2.0 feed. * @param uri RSS 2.0 feed URI * @return in-memory representation of downloaded RSS feed * @throws RSSReaderException if RSS feed could not be retrieved because ofHTTP error * @throws RSSFault if an unrecoverable IO error has occurred */ public RSSFeed load(String uri) throws RSSReaderException { final HttpGet httpget=new HttpGet(uri); InputStream feedStream=null; try { final HttpResponse response=httpclient.execute(httpget); final StatusLine status=response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { throw new RSSReaderException(status.getStatusCode(),status.getReasonPhrase()); } HttpEntity entity=response.getEntity(); feedStream=entity.getContent(); RSSFeed feed=parser.parse(feedStream); if (feed.getLink() == null) { feed.setLink(android.net.Uri.parse(uri)); } return feed; } catch ( ClientProtocolException e) { throw new RSSFault(e); } catch ( IOException e) { throw new RSSFault(e); } finally { Resources.closeQuietly(feedStream); } }
Example 22
From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/synchronisation/tracks/.
Source file: WebClient.java

protected synchronized boolean deleteUrl(String url) throws ApiException { if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } HttpClient client=CreateClient(); java.net.URI uri=URI.create(url); HttpHost host=GetHost(uri); HttpDelete request=new HttpDelete(uri.getPath()); request.setHeader("User-Agent",sUserAgent); try { HttpResponse response=client.execute(host,request); StatusLine status=response.getStatusLine(); Log.i(cTag,"delete with response " + status.toString()); return status.getStatusCode() == HttpStatus.SC_OK; } catch ( IOException e) { throw new ApiException("Problem communicating with API",e); } }
Example 23
From project Android-SyncAdapter-JSON-Server-Example, under directory /src/com/example/android/samplesync/client/.
Source file: NetworkUtilities.java

/** * Fetches the list of friend data updates from the server * @param account The account being synced. * @param authtoken The authtoken stored in AccountManager for this account * @param lastUpdated The last time that sync was performed * @return list The list of updates received from the server. */ public static List<User> fetchFriendUpdates(Account account,String authtoken,Date lastUpdated) throws JSONException, ParseException, IOException, AuthenticationException { final ArrayList<User> friendList=new ArrayList<User>(); final ArrayList<NameValuePair> params=new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME,account.name)); params.add(new BasicNameValuePair(PARAM_PASSWORD,authtoken)); if (lastUpdated != null) { final SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MM/dd HH:mm"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); params.add(new BasicNameValuePair(PARAM_UPDATED,formatter.format(lastUpdated))); } Log.i(TAG,params.toString()); HttpEntity entity=null; entity=new UrlEncodedFormEntity(params); final HttpPost post=new HttpPost(FETCH_FRIEND_UPDATES_URI); post.addHeader(entity.getContentType()); post.setEntity(entity); maybeCreateHttpClient(); final HttpResponse resp=mHttpClient.execute(post); final String response=EntityUtils.toString(resp.getEntity()); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { final JSONArray friends=new JSONArray(response); Log.d(TAG,response); for (int i=0; i < friends.length(); i++) { friendList.add(User.valueOf(friends.getJSONObject(i))); } } else { if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { Log.e(TAG,"Authentication exception in fetching remote contacts"); throw new AuthenticationException(); } else { Log.e(TAG,"Server error in fetching remote contacts: " + resp.getStatusLine()); throw new IOException(); } } return friendList; }
Example 24
From project android-tether, under directory /src/og/android/tether/.
Source file: DeviceRegistrar.java

public static void registerWithServer(final Context context,final String deviceRegistrationID){ new Thread(new Runnable(){ public void run(){ try { HttpResponse res=makeRequest(context,deviceRegistrationID,REGISTER_PATH); if (res.getStatusLine().getStatusCode() == 200) { Log.i(TAG,"Registration with server complete"); Editor editor=prefs(context).edit(); editor.putBoolean("c2dm_registered",true); editor.commit(); } else { Log.w(TAG,"Registration error " + String.valueOf(res.getStatusLine().getStatusCode())); } } catch ( Exception e) { Log.w(TAG,"Registration error " + e.getMessage()); } } } ).start(); }
Example 25
From project AndroidDevWeekendDub-BookLibrary, under directory /src/org/curiouscreature/android/shelves/provider/.
Source file: BooksStore.java

/** * Executes an HTTP request on a REST web service. If the response is ok, the content is sent to the specified response handler. * @param host * @param get The GET request to executed. * @param handler The handler which will parse the response. * @throws java.io.IOException */ private void executeRequest(HttpHost host,HttpGet get,ResponseHandler handler) throws IOException { HttpEntity entity=null; try { final HttpResponse response=HttpManager.execute(host,get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity=response.getEntity(); final InputStream in=entity.getContent(); handler.handleResponse(in); } } finally { if (entity != null) { entity.consumeContent(); } } }
Example 26
From project Android_1, under directory /GsonJsonWebservice/src/com/novoda/activity/.
Source file: JsonRequest.java

private InputStream retrieveStream(String url){ DefaultHttpClient client=new DefaultHttpClient(); HttpGet getRequest=new HttpGet(url); try { HttpResponse getResponse=client.execute(getRequest); final int statusCode=getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(),"Error " + statusCode + " for URL "+ url); return null; } HttpEntity getResponseEntity=getResponse.getEntity(); return getResponseEntity.getContent(); } catch ( IOException e) { getRequest.abort(); Log.w(getClass().getSimpleName(),"Error for URL " + url,e); } return null; }
Example 27
From project android_7, under directory /src/org/immopoly/android/helper/.
Source file: WebHelper.java

public static JSONArray postFlatIdsHttpData(String url,JSONObject jsonObject) throws JSONException { try { InputStream in; HttpResponse response=postHttp(url,jsonObject); Header contentEncoding=response.getFirstHeader("Content-Encoding"); if (response != null && contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { in=new GZIPInputStream(response.getEntity().getContent()); } else { in=new BufferedInputStream(response.getEntity().getContent()); } String s=readInputStream(in); return new JSONArray(s); } catch ( IOException e) { e.printStackTrace(); } return null; }
Example 28
From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/.
Source file: RadioInfo.java

/** * This function checks for basic functionality of HTTP Client. */ private void httpClientTest(){ HttpClient client=new DefaultHttpClient(); try { HttpGet request=new HttpGet("http://www.google.com"); HttpResponse response=client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { mHttpClientTestResult="Pass"; } else { mHttpClientTestResult="Fail: Code: " + String.valueOf(response); } request.abort(); } catch ( IOException e) { mHttpClientTestResult="Fail: IOException"; } }
Example 29
From project android_external_oauth, under directory /core/src/main/java/net/oauth/client/httpclient4/.
Source file: HttpClient4.java

public HttpResponseMessage execute(HttpMessage request) throws IOException { final String method=request.method; final String url=request.url.toExternalForm(); final InputStream body=request.getBody(); final boolean isDelete=DELETE.equalsIgnoreCase(method); final boolean isPost=POST.equalsIgnoreCase(method); final boolean isPut=PUT.equalsIgnoreCase(method); byte[] excerpt=null; HttpRequestBase httpRequest; if (isPost || isPut) { HttpEntityEnclosingRequestBase entityEnclosingMethod=isPost ? new HttpPost(url) : new HttpPut(url); if (body != null) { ExcerptInputStream e=new ExcerptInputStream(body); excerpt=e.getExcerpt(); String length=request.removeHeaders(HttpMessage.CONTENT_LENGTH); entityEnclosingMethod.setEntity(new InputStreamEntity(e,(length == null) ? -1 : Long.parseLong(length))); } httpRequest=entityEnclosingMethod; } else if (isDelete) { httpRequest=new HttpDelete(url); } else { httpRequest=new HttpGet(url); } for ( Map.Entry<String,String> header : request.headers) { httpRequest.addHeader(header.getKey(),header.getValue()); } HttpClient client=clientPool.getHttpClient(new URL(httpRequest.getURI().toString())); client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,false); HttpResponse httpResponse=client.execute(httpRequest); return new HttpMethodResponse(httpRequest,httpResponse,excerpt,request.getContentCharset()); }
Example 30
From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.
Source file: UriTexture.java

private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri,ClientConnectionManager connectionManager){ InputStream contentInput=null; if (connectionManager == null) { try { URL url=new URI(uri).toURL(); URLConnection conn=url.openConnection(); conn.connect(); contentInput=conn.getInputStream(); } catch ( Exception e) { Log.w(TAG,"Request failed: " + uri); e.printStackTrace(); return null; } } else { final DefaultHttpClient mHttpClient=new DefaultHttpClient(connectionManager,HTTP_PARAMS); HttpUriRequest request=new HttpGet(uri); HttpResponse httpResponse=null; try { httpResponse=mHttpClient.execute(request); HttpEntity entity=httpResponse.getEntity(); if (entity != null) { contentInput=entity.getContent(); } } catch ( Exception e) { Log.w(TAG,"Request failed: " + request.getURI()); return null; } } if (contentInput != null) { return new BufferedInputStream(contentInput,4096); } else { return null; } }
Example 31
From project andstatus, under directory /src/org/andstatus/app/net/.
Source file: ConnectionBasicAuth.java

/** * Execute a GET request against the Twitter REST API. * @param url * @param client * @return String * @throws ConnectionException */ private String getRequest(String url,HttpClient client) throws ConnectionException { String result=null; int statusCode=0; HttpGet getMethod=new HttpGet(url); try { getMethod.setHeader("User-Agent",USER_AGENT); getMethod.addHeader("Authorization","Basic " + getCredentials()); client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,DEFAULT_GET_REQUEST_TIMEOUT); client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,DEFAULT_GET_REQUEST_TIMEOUT); HttpResponse httpResponse=client.execute(getMethod); statusCode=httpResponse.getStatusLine().getStatusCode(); result=retrieveInputStream(httpResponse.getEntity()); } catch ( Exception e) { Log.e(TAG,"getRequest: " + e.toString()); throw new ConnectionException(e); } finally { getMethod.abort(); } parseStatusCode(statusCode,url); return result; }
Example 32
From project andtweet, under directory /src/com/xorcode/andtweet/net/.
Source file: ConnectionBasicAuth.java

/** * Execute a GET request against the Twitter REST API. * @param url * @param client * @return String * @throws ConnectionException */ private String getRequest(String url,HttpClient client) throws ConnectionException { String result=null; int statusCode=0; HttpGet getMethod=new HttpGet(url); try { getMethod.setHeader("User-Agent",USER_AGENT); getMethod.addHeader("Authorization","Basic " + getCredentials()); client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,DEFAULT_GET_REQUEST_TIMEOUT); client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,DEFAULT_GET_REQUEST_TIMEOUT); HttpResponse httpResponse=client.execute(getMethod); statusCode=httpResponse.getStatusLine().getStatusCode(); result=retrieveInputStream(httpResponse.getEntity()); } catch ( Exception e) { Log.e(TAG,"getRequest: " + e.toString()); throw new ConnectionException(e); } finally { getMethod.abort(); } parseStatusCode(statusCode,url); return result; }
Example 33
From project Anki-Android, under directory /src/com/ichi2/anki/.
Source file: AnkiDroidProxy.java

public String getDecks(){ String decksServer="{}"; try { String data="p=" + URLEncoder.encode(mPassword,"UTF-8") + "&client=ankidroid-0.4&u="+ URLEncoder.encode(mUsername,"UTF-8")+ "&d=None&sources="+ URLEncoder.encode("[]","UTF-8")+ "&libanki=0.9.9.8.6&pversion=5"; HttpPost httpPost=new HttpPost(SYNC_URL + "getDecks"); StringEntity entity=new StringEntity(data); httpPost.setEntity(entity); httpPost.setHeader("Accept-Encoding","identity"); httpPost.setHeader("Content-type","application/x-www-form-urlencoded"); DefaultHttpClient httpClient=new DefaultHttpClient(); HttpResponse response=httpClient.execute(httpPost); Log.i(AnkiDroidApp.TAG,"Response = " + response.toString()); HttpEntity entityResponse=response.getEntity(); Log.i(AnkiDroidApp.TAG,"Entity's response = " + entityResponse.toString()); InputStream content=entityResponse.getContent(); Log.i(AnkiDroidApp.TAG,"Content = " + content.toString()); decksServer=Utils.convertStreamToString(new InflaterInputStream(content)); Log.i(AnkiDroidApp.TAG,"String content = " + decksServer); } catch ( UnsupportedEncodingException e) { e.printStackTrace(); } catch ( ClientProtocolException e) { Log.i(AnkiDroidApp.TAG,"ClientProtocolException = " + e.getMessage()); } catch ( IOException e) { Log.i(AnkiDroidApp.TAG,"IOException = " + e.getMessage()); } return decksServer; }
Example 34
From project api-sdk-java, under directory /api-sdk/src/main/java/com/smartling/api/sdk/file/.
Source file: FileApiClientAdapterImpl.java

private StringResponse executeHttpcall(HttpRequestBase httpRequest) throws FileApiException { HttpClient httpClient=null; try { httpClient=new DefaultHttpClient(); setupProxy(httpClient); HttpResponse response=httpClient.execute(httpRequest); if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) return inputStreamToString(response.getEntity().getContent(),null); throw new FileApiException(inputStreamToString(response.getEntity().getContent(),null).getContents()); } catch ( IOException e) { throw new FileApiException(e); } finally { if (null != httpClient) httpClient.getConnectionManager().shutdown(); } }
Example 35
From project apps-for-android, under directory /Panoramio/src/com/google/android/panoramio/.
Source file: ImageManager.java

@Override public void run(){ String url=THUMBNAIL_URL; url=String.format(url,mMinLat,mMinLong,mMaxLat,mMaxLong); try { URI uri=new URI("http",url,null); HttpGet get=new HttpGet(uri); HttpClient client=new DefaultHttpClient(); HttpResponse response=client.execute(get); HttpEntity entity=response.getEntity(); String str=convertStreamToString(entity.getContent()); JSONObject json=new JSONObject(str); parse(json); } catch ( Exception e) { Log.e(TAG,e.toString()); } }
Example 36
From project AquaNotesTest, under directory /src/com/google/android/apps/iosched/io/.
Source file: RemoteExecutor.java

/** * Execute this {@link HttpUriRequest}, passing a valid response through {@link XmlHandler#parseAndApply(XmlPullParser,ContentResolver)}. */ public void execute(HttpUriRequest request,XmlHandler handler) throws HandlerException { try { final HttpResponse resp=mHttpClient.execute(request); final int status=resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { throw new HandlerException("Unexpected server response " + resp.getStatusLine() + " for "+ request.getRequestLine()); } final InputStream input=resp.getEntity().getContent(); try { final XmlPullParser parser=ParserUtils.newPullParser(input); handler.parseAndApply(parser,mResolver); } catch ( XmlPullParserException e) { throw new HandlerException("Malformed response for " + request.getRequestLine(),e); } finally { if (input != null) input.close(); } } catch ( HandlerException e) { throw e; } catch ( IOException e) { throw new HandlerException("Problem reading remote response for " + request.getRequestLine(),e); } }
Example 37
From project aranea, under directory /webapp/src/test/java/no/dusken/aranea/integration/test/.
Source file: AbstractIntegrationTest.java

private void checkValidity(){ try { HttpPost post=new HttpPost("http://validator.w3.org/check"); List<NameValuePair> formparams=new ArrayList<NameValuePair>(); String pageSource=webDriver.getPageSource(); formparams.add(new BasicNameValuePair("fragment",pageSource)); formparams.add(new BasicNameValuePair("output","json")); UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formparams,"UTF-8"); post.setEntity(entity); HttpResponse httpResponse=httpclient.execute(post); HttpEntity responseEntity=httpResponse.getEntity(); Map values=mapper.readValue(responseEntity.getContent(),Map.class); checkValues((List<Map<String,Object>>)values.get("messages")); } catch ( IOException e) { fail("Error when checking validity: " + e.getMessage()); e.printStackTrace(); } }
Example 38
From project azure4j-blog-samples, under directory /ACSManagementService/src/com/persistent/azure/acs/.
Source file: ACSAuthenticationHelper.java

/** * Get OAuth SWT token from ACS */ private String getTokenFromACS(String acsNamespace,String acsMgmtPassword){ try { DefaultHttpClient httpClient=new DefaultHttpClient(); HttpPost httpPost=new HttpPost(String.format(ACSAuthenticationHelper.AcsTokenServiceUrl,acsNamespace)); List<NameValuePair> listNameValuePairs=new ArrayList<NameValuePair>(); listNameValuePairs.add(new BasicNameValuePair("grant_type","client_credentials")); listNameValuePairs.add(new BasicNameValuePair("client_id",managementUserName)); listNameValuePairs.add(new BasicNameValuePair("client_secret",acsMgmtPassword)); listNameValuePairs.add(new BasicNameValuePair("scope",String.format(ACSAuthenticationHelper.AcsODataServiceUrl,acsNamespace))); UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(listNameValuePairs); httpPost.setEntity(formEntity); HttpResponse httpResponse=httpClient.execute(httpPost); HttpEntity entity=httpResponse.getEntity(); InputStream inputStream=entity.getContent(); InputStreamReader streamReader=new InputStreamReader(inputStream); BufferedReader bufferedReader=new BufferedReader(streamReader); String string=null; StringBuffer response=new StringBuffer(); while ((string=bufferedReader.readLine()) != null) { response.append(string); } JSONObject obj=new JSONObject(response.toString()); return obj.getString("access_token"); } catch ( Exception e) { e.printStackTrace(); return null; } }
Example 39
From project b3log-latke, under directory /latke-client/src/main/java/org/b3log/latke/client/.
Source file: LatkeClient.java

/** * Gets repository names. * @return repository names * @throws Exception exception */ private static Set<String> getRepositoryNames() throws Exception { final HttpClient httpClient=new DefaultHttpClient(); final List<NameValuePair> qparams=new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("userName",userName)); qparams.add(new BasicNameValuePair("password",password)); final URI uri=URIUtils.createURI("http",serverAddress,-1,GET_REPOSITORY_NAMES,URLEncodedUtils.format(qparams,"UTF-8"),null); final HttpGet request=new HttpGet(); request.setURI(uri); if (verbose) { System.out.println("Getting repository names[" + GET_REPOSITORY_NAMES + "]"); } final HttpResponse httpResponse=httpClient.execute(request); final InputStream contentStream=httpResponse.getEntity().getContent(); final String content=IOUtils.toString(contentStream).trim(); if (verbose) { printResponse(content); } final JSONObject result=new JSONObject(content); final JSONArray repositoryNames=result.getJSONArray("repositoryNames"); final Set<String> ret=new HashSet<String>(); for (int i=0; i < repositoryNames.length(); i++) { final String repositoryName=repositoryNames.getString(i); ret.add(repositoryName); final File dir=new File(backupDir.getPath() + File.separatorChar + repositoryName); if (!dir.exists() && verbose) { dir.mkdir(); System.out.println("Created a directory[name=" + dir.getName() + "] under backup directory[path="+ backupDir.getPath()+ "]"); } } return ret; }
Example 40
From project basiclti-portlet, under directory /src/main/java/au/edu/anu/portal/portlets/basiclti/support/.
Source file: HttpSupport.java

/** * Make a POST request with the given Map of parameters to be encoded * @param address address to POST to * @param params Map of params to use as the form parameters * @return */ public static String doPost(String address,Map<String,String> params){ HttpClient httpclient=new DefaultHttpClient(); try { HttpPost httppost=new HttpPost(address); List<NameValuePair> formparams=new ArrayList<NameValuePair>(); for ( Map.Entry<String,String> entry : params.entrySet()) { formparams.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); } UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formparams,HTTP.UTF_8); httppost.setEntity(entity); HttpResponse response=httpclient.execute(httppost); String responseContent=EntityUtils.toString(response.getEntity()); return responseContent; } catch ( Exception e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } return null; }
Example 41
From project BBC-News-Reader, under directory /src/org/mcsoxford/rss/.
Source file: RSSReader.java

/** * Send HTTP GET request and parse the XML response to construct an in-memory representation of an RSS 2.0 feed. * @param uri RSS 2.0 feed URI * @return in-memory representation of downloaded RSS feed * @throws RSSReaderException if RSS feed could not be retrieved because ofHTTP error * @throws RSSFault if an unrecoverable IO error has occurred */ public RSSFeed load(String uri) throws RSSReaderException { final HttpGet httpget=new HttpGet(uri); InputStream feed=null; try { final HttpResponse response=httpclient.execute(httpget); final StatusLine status=response.getStatusLine(); if (status.getStatusCode() != HttpStatus.SC_OK) { throw new RSSReaderException(status.getStatusCode(),status.getReasonPhrase()); } HttpEntity entity=response.getEntity(); feed=entity.getContent(); return parser.parse(feed); } catch ( ClientProtocolException e) { throw new RSSFault(e); } catch ( IOException e) { throw new RSSFault(e); } finally { Resources.closeQuietly(feed); } }
Example 42
From project be.norio.twunch.android, under directory /src/com/google/android/apps/iosched/io/.
Source file: RemoteExecutor.java

/** * Execute this {@link HttpUriRequest}, passing a valid response through {@link XmlHandler#parseAndApply(XmlPullParser,ContentResolver)}. */ public void execute(HttpUriRequest request,XmlHandler handler) throws HandlerException { try { final HttpResponse resp=mHttpClient.execute(request); final int status=resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { throw new HandlerException("Unexpected server response " + resp.getStatusLine() + " for "+ request.getRequestLine()); } final InputStream input=resp.getEntity().getContent(); try { final XmlPullParser parser=ParserUtils.newPullParser(input); handler.parseAndApply(parser,mResolver); } catch ( XmlPullParserException e) { throw new HandlerException("Malformed response for " + request.getRequestLine(),e); } finally { if (input != null) input.close(); } } catch ( HandlerException e) { throw e; } catch ( IOException e) { throw new HandlerException("Problem reading remote response for " + request.getRequestLine(),e); } }
Example 43
From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.
Source file: LoaderImageView.java

private static Drawable getDrawableFromUrl(final String url) throws IOException, MalformedURLException { try { HttpGet httpRequest=new HttpGet(new URL(url).toURI()); HttpClient httpClient=new DefaultHttpClient(); HttpResponse response=(HttpResponse)httpClient.execute(httpRequest); HttpEntity entity=response.getEntity(); BufferedHttpEntity bufHttpEntity=new BufferedHttpEntity(entity); final long contentLength=bufHttpEntity.getContentLength(); if (contentLength >= 0) { InputStream is=bufHttpEntity.getContent(); return Drawable.createFromStream(is,"name"); } else { return null; } } catch ( Exception e) { e.printStackTrace(); } return null; }
Example 44
From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/webservice/.
Source file: AVService.java

@Override protected HttpResponse[] doInBackground(ArrayList<Object>... params){ HttpResponse[] response=new HttpResponse[2]; int i=0; for ( ArrayList<Object> PicArray : params) { if (PicArray != null) { HttpClient httpClient=new DefaultHttpClient(); HttpContext localContext=new BasicHttpContext(); HttpPost httpPost=new HttpPost((String)PicArray.get(0)); httpPost.addHeader("udid",(String)PicArray.get(1)); Log.d(Constants.PROJECT_TAG,"length : " + ((String)PicArray.get(2)).length()); httpPost.addHeader("img_comment",(String)PicArray.get(2)); httpPost.addHeader("incident_id",(String)PicArray.get(3)); httpPost.addHeader("type",(String)PicArray.get(4)); if (((Boolean)PicArray.get(6)).booleanValue()) { httpPost.addHeader("INCIDENT_CREATION","true"); } try { FileEntity file=new FileEntity((File)PicArray.get(5),"image/jpeg"); file.setContentType("image/jpeg"); httpPost.setEntity(file); response[i++]=httpClient.execute(httpPost,localContext); } catch ( IOException e) { Log.e(Constants.PROJECT_TAG,"IOException postImage",e); } catch ( IllegalStateException e) { Log.e(Constants.PROJECT_TAG,"IllegalStateException postImage",e); } } } return response; }
Example 45
From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/oauth/signpost/commonshttp/.
Source file: CommonsHttpOAuthProvider.java

@Override protected void closeConnection(HttpRequest request,com.nostra13.socialsharing.twitter.extpack.oauth.signpost.http.HttpResponse response) throws Exception { if (response != null) { HttpEntity entity=((HttpResponse)response.unwrap()).getEntity(); if (entity != null) { try { entity.consumeContent(); } catch ( IOException e) { e.printStackTrace(); } } } }