Java Code Examples for org.apache.http.client.methods.HttpUriRequest

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 GeekAlarm, under directory /android/src/com/geek_alarm/android/tasks/.

Source file: TaskManager.java

  27 
vote

private static HttpEntity sendRequest(String url) throws Exception {
  HttpClient client=new DefaultHttpClient();
  HttpUriRequest request=new HttpGet(SERVER_URL + url);
  HttpResponse response=client.execute(request);
  return response.getEntity();
}
 

Example 2

From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-cxf-interceptor/src/test/java/org/easysoa/cxf/.

Source file: ProxyInterceptorTest.java

  25 
vote

@Test public void InterceptorTest() throws IllegalStateException, Exception {
  DefaultHttpClient httpClient=new DefaultHttpClient();
  HttpUriRequest httpUriRequest;
  httpUriRequest=new HttpGet("http://localhost:9910/?wsdl");
  HttpResponse response=httpClient.execute(httpUriRequest);
  String entityResponseString=ContentReader.read(response.getEntity().getContent());
  logger.debug(entityResponseString);
}
 

Example 3

From project httpcache4j, under directory /resolvers/resolvers-httpcomponents-httpclient/src/test/java/org/codehaus/httpcache4j/resolver/.

Source file: HTTPClientResponseResolverTest.java

  23 
vote

@Override protected HttpUriRequest getMethod(HTTPMethod method,URI requestURI){
  HttpUriRequest request=mock(HttpUriRequest.class);
  when(request.getMethod()).thenReturn(method.toString());
  when(request.getURI()).thenReturn(requestURI);
  return request;
}
 

Example 4

From project OpenConext-api, under directory /coin-api-war/src/test/java/nl/surfnet/coin/selenium/.

Source file: CorsHeaderTestSelenium.java

  23 
vote

@Test public void preflight() throws Exception {
  HttpClient client=new DefaultHttpClient();
  HttpUriRequest req=new HttpOptions(getApiBaseUrl() + OS_URL);
  req.setHeader("Origin","localhost");
  client.execute(req,new ResponseHandler<Object>(){
    @Override public Object handleResponse(    HttpResponse response) throws ClientProtocolException, IOException {
      System.out.println("Response of preflight request: " + response.toString());
      assertThat("response header Access-Control-Allow-Methods should contain 'GET'",response.getFirstHeader("Access-Control-Allow-Methods").getValue(),containsString("GET"));
      assertThat("No content should be served on a preflight request",response.getEntity().getContentLength(),equalTo(0L));
      return null;
    }
  }
);
}
 

Example 5

From project OpenTripPlanner-for-Android, under directory /src/de/mastacode/http/.

Source file: Http.java

  23 
vote

private HttpUriRequest createFinalRequest() throws IOException {
  final HttpUriRequest request=createRequest();
  applyHeaders(request);
  if (followRedirects != null) {
    HttpClientParams.setRedirecting(request.getParams(),followRedirects);
  }
  applyCustomizers(request);
  return request;
}
 

Example 6

From project Vega, under directory /platform/com.subgraph.vega.scanner/src/com/subgraph/vega/impl/scanner/handlers/.

Source file: DirParentCheck.java

  23 
vote

public void initialize(IPathState ps){
  if (!ps.has404Fingerprints() || !hasSuitablePath(ps)) {
    ipsCheck.initialize(ps);
    return;
  }
  final IInjectionModuleContext ctx=ps.createModuleContext();
  final HttpUriRequest req=createRequest(ps.getPath());
  ctx.submitRequest(req,this,0);
}
 

Example 7

From project httpClient, under directory /httpclient/src/test/java/org/apache/http/impl/client/.

Source file: TestDefaultHttpRequestRetryHandler.java

  22 
vote

@Test public void noRetryOnConnectTimeout() throws Exception {
  HttpContext context=mock(HttpContext.class);
  HttpUriRequest request=mock(HttpUriRequest.class);
  DefaultHttpRequestRetryHandler retryHandler=new DefaultHttpRequestRetryHandler();
  Assert.assertEquals(3,retryHandler.getRetryCount());
  when(request.isAborted()).thenReturn(Boolean.FALSE);
  when(context.getAttribute(ExecutionContext.HTTP_REQUEST)).thenReturn(request);
  Assert.assertFalse(retryHandler.retryRequest(new ConnectTimeoutException(),1,context));
}
 

Example 8

From project huiswerk, under directory /print/zxing-1.6/android/src/com/google/zxing/client/android/book/.

Source file: SearchBookContentsActivity.java

  22 
vote

private static String getCookie(String url){
  String cookie=CookieManager.getInstance().getCookie(url);
  if (cookie == null || cookie.length() == 0) {
    Log.d(TAG,"Book Search cookie was missing or expired");
    HttpUriRequest head=new HttpHead(url);
    AndroidHttpClient client=AndroidHttpClient.newInstance(USER_AGENT);
    try {
      HttpResponse response=client.execute(head);
      if (response.getStatusLine().getStatusCode() == 200) {
        Header[] cookies=response.getHeaders("set-cookie");
        for (        Header theCookie : cookies) {
          CookieManager.getInstance().setCookie(url,theCookie.getValue());
        }
        CookieSyncManager.getInstance().sync();
        cookie=CookieManager.getInstance().getCookie(url);
      }
    }
 catch (    IOException e) {
      Log.w(TAG,"Error setting book search cookie",e);
    }
    client.close();
  }
  return cookie;
}
 

Example 9

From project rest-driver, under directory /rest-server-driver/src/main/java/com/github/restdriver/serverdriver/http/.

Source file: ByteArrayRequestBody.java

  22 
vote

@Override public void applyTo(ServerDriverHttpUriRequest request){
  HttpUriRequest internalRequest=request.getHttpUriRequest();
  if (!(internalRequest instanceof HttpEntityEnclosingRequest)) {
    return;
  }
  HttpEntityEnclosingRequest entityRequest=(HttpEntityEnclosingRequest)internalRequest;
  entityRequest.setHeader("Content-type",contentType);
  ByteArrayEntity entity=new ByteArrayEntity(content);
  entity.setContentType(contentType);
  entityRequest.setEntity(entity);
}
 

Example 10

From project rewrite, under directory /test-harness/src/main/java/org/ocpsoft/rewrite/test/.

Source file: HttpAction.java

  22 
vote

/** 
 * Return the current full URL.
 */
public String getCurrentURL(){
  HttpUriRequest currentReq=(HttpUriRequest)context.getAttribute(ExecutionContext.HTTP_REQUEST);
  HttpHost currentHost=(HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  String currentUrl=currentHost.toURI() + currentReq.getURI();
  if (currentUrl.startsWith(baseUrl)) {
    currentUrl=currentUrl.substring(baseUrl.length());
  }
  return currentUrl;
}
 

Example 11

From project Subsonic-Android, under directory /src/net/sourceforge/subsonic/androidapp/service/.

Source file: RESTMusicService.java

  22 
vote

private void detectRedirect(String originalUrl,Context context,HttpContext httpContext){
  HttpUriRequest request=(HttpUriRequest)httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
  HttpHost host=(HttpHost)httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  String redirectedUrl=host.toURI() + request.getURI();
  redirectFrom=originalUrl.substring(0,originalUrl.indexOf("/rest/"));
  redirectTo=redirectedUrl.substring(0,redirectedUrl.indexOf("/rest/"));
  Log.i(TAG,redirectFrom + " redirects to " + redirectTo);
  redirectionLastChecked=System.currentTimeMillis();
  redirectionNetworkType=getCurrentNetworkType(context);
}
 

Example 12

From project subsonic_1, under directory /subsonic-android/src/net/sourceforge/subsonic/androidapp/service/.

Source file: RESTMusicService.java

  22 
vote

private void detectRedirect(String originalUrl,Context context,HttpContext httpContext){
  HttpUriRequest request=(HttpUriRequest)httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
  HttpHost host=(HttpHost)httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  String redirectedUrl=host.toURI() + request.getURI();
  redirectFrom=originalUrl.substring(0,originalUrl.indexOf("/rest/"));
  redirectTo=redirectedUrl.substring(0,redirectedUrl.indexOf("/rest/"));
  Log.i(TAG,redirectFrom + " redirects to " + redirectTo);
  redirectionLastChecked=System.currentTimeMillis();
  redirectionNetworkType=getCurrentNetworkType(context);
}
 

Example 13

From project subsonic_2, under directory /subsonic-android/src/net/sourceforge/subsonic/androidapp/service/.

Source file: RESTMusicService.java

  22 
vote

private void detectRedirect(String originalUrl,Context context,HttpContext httpContext){
  HttpUriRequest request=(HttpUriRequest)httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
  HttpHost host=(HttpHost)httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  String redirectedUrl=host.toURI() + request.getURI();
  redirectFrom=originalUrl.substring(0,originalUrl.indexOf("/rest/"));
  redirectTo=redirectedUrl.substring(0,redirectedUrl.indexOf("/rest/"));
  Log.i(TAG,redirectFrom + " redirects to " + redirectTo);
  redirectionLastChecked=System.currentTimeMillis();
  redirectionNetworkType=getCurrentNetworkType(context);
}
 

Example 14

From project Supersonic, under directory /subsonic-android/src/net/sourceforge/subsonic/androidapp/service/.

Source file: RESTMusicService.java

  22 
vote

private void detectRedirect(String originalUrl,Context context,HttpContext httpContext){
  HttpUriRequest request=(HttpUriRequest)httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
  HttpHost host=(HttpHost)httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  String redirectedUrl=host.toURI() + request.getURI();
  redirectFrom=originalUrl.substring(0,originalUrl.indexOf("/rest/"));
  redirectTo=redirectedUrl.substring(0,redirectedUrl.indexOf("/rest/"));
  Log.i(TAG,redirectFrom + " redirects to " + redirectTo);
  redirectionLastChecked=System.currentTimeMillis();
  redirectionNetworkType=getCurrentNetworkType(context);
}
 

Example 15

From project android-async-http, under directory /src/com/loopj/android/http/.

Source file: RetryHandler.java

  21 
vote

public boolean retryRequest(IOException exception,int executionCount,HttpContext context){
  boolean retry=true;
  Boolean b=(Boolean)context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
  boolean sent=(b != null && b.booleanValue());
  if (executionCount > maxRetries) {
    retry=false;
  }
 else   if (exceptionBlacklist.contains(exception.getClass())) {
    retry=false;
  }
 else   if (exceptionWhitelist.contains(exception.getClass())) {
    retry=true;
  }
 else   if (!sent) {
    retry=true;
  }
  if (retry) {
    HttpUriRequest currentReq=(HttpUriRequest)context.getAttribute(ExecutionContext.HTTP_REQUEST);
    String requestType=currentReq.getMethod();
    retry=!requestType.equals("POST");
  }
  if (retry) {
    SystemClock.sleep(RETRY_SLEEP_TIME_MILLIS);
  }
 else {
    exception.printStackTrace();
  }
  return retry;
}
 

Example 16

From project android-bankdroid, under directory /src/eu/nullbyte/android/urllib/.

Source file: Urllib.java

  21 
vote

public String open(String url,List<NameValuePair> postData,boolean forcePost) throws ClientProtocolException, IOException {
  this.currentURI=url;
  String response;
  String[] headerKeys=(String[])this.headers.keySet().toArray(new String[headers.size()]);
  String[] headerVals=(String[])this.headers.values().toArray(new String[headers.size()]);
  ResponseHandler<String> responseHandler=new BasicResponseHandler();
  HttpUriRequest request;
  if ((postData == null || postData.isEmpty()) && !forcePost) {
    request=new HttpGet(url);
  }
 else {
    request=new HttpPost(url);
    ((HttpPost)request).setEntity(new UrlEncodedFormEntity(postData,this.charset));
  }
  if (userAgent != null)   request.addHeader("User-Agent",userAgent);
  for (int i=0; i < headerKeys.length; i++) {
    request.addHeader(headerKeys[i],headerVals[i]);
  }
  response=httpclient.execute(request,responseHandler,context);
  this.currentURI=request.getURI().toString();
  return response;
}
 

Example 17

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.

Source file: UriTexture.java

  21 
vote

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 18

From project bbb-java, under directory /src/main/java/org/mconf/bbb/api/.

Source file: JoinServiceBase.java

  21 
vote

public int standardJoin(String joinUrl){
  joinedMeeting=new JoinedMeeting();
  try {
    HttpClient client=new DefaultHttpClient();
    HttpGet method=new HttpGet(joinUrl);
    HttpContext context=new BasicHttpContext();
    HttpResponse httpResponse=client.execute(method,context);
    if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)     log.debug("HTTP GET {} return {}",joinUrl,httpResponse.getStatusLine().getStatusCode());
    HttpUriRequest currentReq=(HttpUriRequest)context.getAttribute(ExecutionContext.HTTP_REQUEST);
    if (!currentReq.getURI().getPath().equals("/client/BigBlueButton.html")) {
      log.error("It was redirected to {} instead of /client/BigBlueButton.html: the server was branded" + " and the HTML name was changed, or it's an error. However, it will continue processing",currentReq.getURI().getPath());
    }
    HttpHost currentHost=(HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    String enterUrl=currentHost.toURI() + "/bigbluebutton/api/enter";
    String enterResponse=getUrl(client,enterUrl).replace("</response>","<server>" + currentHost.toURI() + "</server></response>");
    joinedMeeting.parse(enterResponse);
  }
 catch (  Exception e) {
    e.printStackTrace();
    log.error("Can't join the url {}",joinUrl);
    return E_SERVER_UNREACHABLE;
  }
  return joinResponse();
}
 

Example 19

From project capedwarf-blue, under directory /urlfetch/src/main/java/org/jboss/capedwarf/urlfetch/.

Source file: JBossURLFetchService.java

  21 
vote

public HTTPResponse fetch(final HTTPRequest httpRequest) throws IOException {
  try {
    HttpUriRequest request=new HttpRequestBase(){
      public String getMethod(){
        return httpRequest.getMethod().name();
      }
      public URI getURI(){
        try {
          return httpRequest.getURL().toURI();
        }
 catch (        URISyntaxException e) {
          throw new IllegalStateException(e);
        }
      }
    }
;
    HttpResponse response=getClient().execute(request);
    HTTPResponseHack jhr=new HTTPResponseHack(response);
    jhr.setFinalUrl(httpRequest.getURL());
    return jhr.getResponse();
  }
 catch (  Exception e) {
    IOException ioe=new IOException();
    ioe.initCause(e);
    throw ioe;
  }
}
 

Example 20

From project fanfoudroid, under directory /src/com/ch_linghu/fanfoudroid/http/.

Source file: HttpClient.java

  21 
vote

/** 
 * Create request method, such as POST, GET, DELETE
 * @param httpMethod "GET","POST","DELETE"
 * @param uri ?????RI
 * @param file ???null
 * @param postParams POST???
 * @return httpMethod Request implementations for the various HTTP methodslike GET and POST.
 * @throws HttpException createMultipartEntity ? UrlEncodedFormEntity?????OException
 */
private HttpUriRequest createMethod(String httpMethod,URI uri,File file,ArrayList<BasicNameValuePair> postParams) throws HttpException {
  HttpUriRequest method;
  if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
    HttpPost post=new HttpPost(uri);
    post.getParams().setBooleanParameter("http.protocol.expect-continue",false);
    try {
      HttpEntity entity=null;
      if (null != file) {
        entity=createMultipartEntity("photo",file,postParams);
        post.setEntity(entity);
      }
 else       if (null != postParams) {
        entity=new UrlEncodedFormEntity(postParams,HTTP.UTF_8);
      }
      post.setEntity(entity);
    }
 catch (    IOException ioe) {
      throw new HttpException(ioe.getMessage(),ioe);
    }
    method=post;
  }
 else   if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
    method=new HttpDelete(uri);
  }
 else {
    method=new HttpGet(uri);
  }
  return method;
}
 

Example 21

From project fed4j, under directory /src/main/java/com/jute/fed4j/engine/component/http/.

Source file: HttpDispatcherImpl_Jakarta.java

  21 
vote

public void run(HttpComponent component){
  this.commponent=component;
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,component.connectTimeout);
  HttpConnectionParams.setSoTimeout(params,component.readTimeout);
  try {
    this.init(component);
    HttpClient httpclient=new MyHttpClient(getConnectionManager(params,component.enablePersistentConnection),params);
    if (component.enableProxy && "http".equals(component.proxyType)) {
      HttpHost proxy=new HttpHost(component.proxyHost,component.proxyPort,component.proxyType);
      httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
    }
    HttpUriRequest request=new HttpRequest(component.method,component.uri);
    MyHttpResponseHandler responseHandler=new MyHttpResponseHandler(component.responseCharset);
    String body=httpclient.execute(request,responseHandler);
    this.onResponse(component,responseHandler.code,body);
  }
 catch (  SocketTimeoutException e) {
    onException(component,-2," socket timeout error occurs: " + e.getMessage());
  }
catch (  ClientProtocolException e) {
    onException(component,-3," error resposed from server: " + e.getMessage());
  }
catch (  IOException e) {
    onException(component,-4," error occurs during dispatch: " + e.getMessage());
  }
catch (  Exception e) {
    onException(component,-5,"error occurs during parsing xml:" + e.getMessage());
  }
}
 

Example 22

From project Fotolia-API, under directory /java/libs/httpcomponents-client-4.1.2/examples/org/apache/http/examples/client/.

Source file: ClientKerberosAuthentication.java

  21 
vote

public static void main(String[] args) throws Exception {
  System.setProperty("java.security.auth.login.config","login.conf");
  System.setProperty("java.security.krb5.conf","krb5.conf");
  System.setProperty("sun.security.krb5.debug","true");
  System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
  DefaultHttpClient httpclient=new DefaultHttpClient();
  try {
    NegotiateSchemeFactory nsf=new NegotiateSchemeFactory();
    httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO,nsf);
    Credentials use_jaas_creds=new Credentials(){
      public String getPassword(){
        return null;
      }
      public Principal getUserPrincipal(){
        return null;
      }
    }
;
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(null,-1,null),use_jaas_creds);
    HttpUriRequest request=new HttpGet("http://kerberoshost/");
    HttpResponse response=httpclient.execute(request);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    System.out.println("----------------------------------------");
    if (entity != null) {
      System.out.println(EntityUtils.toString(entity));
    }
    System.out.println("----------------------------------------");
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 23

From project ihatovgram, under directory /src/client/android/ihatovgram/lib/httpcomponents-client-4.1.3/examples/org/apache/http/examples/client/.

Source file: ClientKerberosAuthentication.java

  21 
vote

public static void main(String[] args) throws Exception {
  System.setProperty("java.security.auth.login.config","login.conf");
  System.setProperty("java.security.krb5.conf","krb5.conf");
  System.setProperty("sun.security.krb5.debug","true");
  System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
  DefaultHttpClient httpclient=new DefaultHttpClient();
  try {
    NegotiateSchemeFactory nsf=new NegotiateSchemeFactory();
    httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO,nsf);
    Credentials use_jaas_creds=new Credentials(){
      public String getPassword(){
        return null;
      }
      public Principal getUserPrincipal(){
        return null;
      }
    }
;
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(null,-1,null),use_jaas_creds);
    HttpUriRequest request=new HttpGet("http://kerberoshost/");
    HttpResponse response=httpclient.execute(request);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    System.out.println("----------------------------------------");
    if (entity != null) {
      System.out.println(EntityUtils.toString(entity));
    }
    System.out.println("----------------------------------------");
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 24

From project isohealth, under directory /Oauth/java/core/httpclient4/src/main/java/net/oauth/client/httpclient4/.

Source file: OAuthScheme.java

  21 
vote

public Header authenticate(Credentials credentials,HttpRequest request) throws AuthenticationException {
  String uri;
  String method;
  HttpUriRequest uriRequest=getHttpUriRequest(request);
  if (uriRequest != null) {
    uri=uriRequest.getURI().toString();
    method=uriRequest.getMethod();
  }
 else {
    RequestLine requestLine=request.getRequestLine();
    uri=requestLine.getUri();
    method=requestLine.getMethod();
  }
  try {
    OAuthMessage message=new OAuthMessage(method,uri,null);
    OAuthAccessor accessor=getAccessor(credentials);
    message.addRequiredParameters(accessor);
    String authorization=message.getAuthorizationHeader(getRealm());
    return new BasicHeader("Authorization",authorization);
  }
 catch (  Exception e) {
    throw new AuthenticationException(null,e);
  }
}
 

Example 25

From project jena-fuseki, under directory /src/main/java/org/apache/jena/fuseki/migrate/.

Source file: WebIO.java

  21 
vote

/** 
 * Simple GET 
 */
public static String exec_get(String url){
  HttpUriRequest httpGet=new HttpGet(url);
  HttpClient httpclient=new DefaultHttpClient();
  try {
    HttpResponse response=httpclient.execute(httpGet);
    int responseCode=response.getStatusLine().getStatusCode();
    String responseMessage=response.getStatusLine().getReasonPhrase();
    if (200 != responseCode)     throw FusekiRequestException.create(responseCode,responseMessage);
    HttpEntity entity=response.getEntity();
    InputStream instream=entity.getContent();
    String string=IO.readWholeFileAsUTF8(instream);
    instream.close();
    return string;
  }
 catch (  IOException ex) {
    IO.exception(ex);
    return null;
  }
}
 

Example 26

From project lightbox-android-webservices, under directory /LightboxAndroidWebServices/src/com/lightbox/android/network/.

Source file: HttpHelper.java

  21 
vote

/** 
 * Call the specified  {@link HttpMethod}.
 * @param method
 * @param uri
 * @param urlParameters Optional.
 * @param body Optional. If you pass a Map, it will be passed as Form-URLEncoded, if you pass an {@link HttpEntity}it will be used directly, otherwise the toString will be used.
 * @param headers Optional.
 * @return the {@link HttpResponse}
 * @throws IOException if the request cannot be sent.
 */
public HttpResponse call(HttpMethod method,URI uri,Map<String,Object> urlParameters,Object body,Map<String,String> headers) throws IOException {
  uri=addQueryParametersToUri(uri,urlParameters);
  HttpUriRequest httpRequest=method.createHttpRequest(uri);
  httpRequest=addBodyToHttpRequest(httpRequest,body);
  httpRequest.setHeader("Accept-Language",Locale.getDefault().toString().replace('_','-'));
  if (headers != null) {
    for (    Map.Entry<String,String> header : headers.entrySet()) {
      httpRequest.setHeader(header.getKey(),header.getValue());
    }
  }
  DebugLog.d(TAG,"Calling %s",uri.toString());
  HttpResponse httpResponse=mHttpClient.execute(httpRequest);
  final int statusCode=httpResponse.getStatusLine().getStatusCode();
  if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
    Header locationHeader=httpResponse.getFirstHeader("Location");
    if (locationHeader != null) {
      String newUrl=locationHeader.getValue();
      return call(method,URI.create(newUrl),urlParameters,body,headers);
    }
  }
  return httpResponse;
}
 

Example 27

From project LoL-Chat, under directory /src/com/rei/lolchat/smack/avatar/.

Source file: HttpClientAvatarRetriever.java

  21 
vote

@Override public byte[] getAvatar() throws IOException {
  HttpUriRequest request;
  try {
    request=new HttpGet(mUrl);
  }
 catch (  IllegalArgumentException e) {
    IOException ioe=new IOException("Invalid url " + mUrl);
    ioe.initCause(e);
    throw ioe;
  }
  HttpResponse response=mClient.execute(request);
  HttpEntity entity=response.getEntity();
  InputStream in=entity.getContent();
  ByteArrayOutputStream os=new ByteArrayOutputStream();
  try {
    byte[] data=new byte[1024];
    int nbread;
    while ((nbread=in.read(data)) != -1) {
      os.write(data,0,nbread);
    }
  }
  finally {
    in.close();
    os.close();
  }
  return os.toByteArray();
}
 

Example 28

From project NotePad, under directory /src/com/nononsenseapps/notepad/sync/googleapi/.

Source file: GoogleAPITalker.java

  21 
vote

/** 
 * Calls the GTasks API and tries to move a task to its target position.
 * @param task
 * @throws ClientProtocolException
 * @throws JSONException
 * @throws IOException
 * @throws PreconditionException
 */
private void moveTask(final GoogleTask task,final GoogleTaskList pList) throws ClientProtocolException, JSONException, IOException, PreconditionException {
  if (pList.id == null || pList.id.isEmpty() || task.id == null || task.id.isEmpty()) {
    Log.d(TAG,"Invalid list ID found for uploadTask");
    return;
  }
  HttpUriRequest httppost=new HttpPost(TaskMoveURL_ETAG_UPDATED(task.id,pList.id,task.remoteparent,task.remoteprevious));
  setAuthHeader(httppost);
  AndroidHttpClient.modifyRequestToAcceptGzipResponse(httppost);
  Log.d(TAG,httppost.getRequestLine().toString());
  for (  Header header : httppost.getAllHeaders()) {
    Log.d(TAG,header.getName() + ": " + header.getValue());
  }
  String stringResponse=parseResponse(client.execute(httppost));
  JSONObject jsonResponse=new JSONObject(stringResponse);
  Log.d(TAG,jsonResponse.toString());
  task.etag=jsonResponse.getString("etag");
  if (jsonResponse.has(GoogleTask.UPDATED))   task.updated=jsonResponse.getString(GoogleTask.UPDATED);
  task.moveUploaded=true;
  if (jsonResponse.has(GoogleTask.PARENT))   task.remoteparent=jsonResponse.getString(GoogleTask.PARENT);
 else   task.remoteparent=null;
  if (jsonResponse.has(GoogleTask.POSITION))   task.position=jsonResponse.getString(GoogleTask.POSITION);
 else   task.position=null;
}
 

Example 29

From project odata4j, under directory /odata4j-cxf/src/main/java/org/odata4j/cxf/consumer/.

Source file: ODataCxfClient.java

  21 
vote

private HttpUriRequest getRequestByMethod(String method,URI uri){
  HttpUriRequest request;
  if ("get".equalsIgnoreCase(method)) {
    request=new HttpGet(uri);
  }
 else   if ("put".equalsIgnoreCase(method)) {
    request=new HttpPut(uri);
  }
 else   if ("post".equalsIgnoreCase(method)) {
    request=new HttpPost(uri);
  }
 else   if ("delete".equalsIgnoreCase(method)) {
    request=new HttpDelete(uri);
  }
 else   if ("options".equalsIgnoreCase(method)) {
    request=new HttpOptions(uri);
  }
 else   if ("head".equalsIgnoreCase(method)) {
    request=new HttpHead(uri);
  }
 else {
    throw new RuntimeException("Method unknown: " + method);
  }
  return request;
}
 

Example 30

From project OpenConext-teams, under directory /coin-teams-scim/src/main/java/nl/surfnet/coin/teams/service/.

Source file: ASyncProvisioningManager.java

  21 
vote

@Async @Override public void groupEvent(String teamId,String displayName,Operation operation){
  try {
    HttpUriRequest request;
    ScimEvent event=new ScimEvent();
    String uriPath=baseUri;
switch (operation) {
case CREATE:
      event.setId(teamId);
    event.setDisplayName(displayName);
  request=new HttpPost(uriPath);
break;
case DELETE:
uriPath=uriPath.concat("/").concat(URLEncoder.encode(teamId,UTF_8));
request=new HttpDelete(uriPath);
break;
case UPDATE:
event.setDisplayName(displayName);
uriPath=uriPath.concat("/").concat(URLEncoder.encode(teamId,UTF_8));
request=new HttpPatch(uriPath);
break;
default :
throw new RuntimeException("Unsupported operation for groupEvent(" + operation + ")");
}
execute(request,event);
}
 catch (Throwable e) {
throw new RuntimeException(e);
}
}
 

Example 31

From project PartyWare, under directory /android/src/com/google/zxing/client/android/book/.

Source file: SearchBookContentsActivity.java

  21 
vote

private static String getCookie(String url){
  String cookie=CookieManager.getInstance().getCookie(url);
  if (cookie == null || cookie.length() == 0) {
    Log.d(TAG,"Book Search cookie was missing or expired");
    HttpUriRequest head=new HttpHead(url);
    AndroidHttpClient client=AndroidHttpClient.newInstance(USER_AGENT);
    try {
      HttpResponse response=client.execute(head);
      if (response.getStatusLine().getStatusCode() == 200) {
        Header[] cookies=response.getHeaders("set-cookie");
        for (        Header theCookie : cookies) {
          CookieManager.getInstance().setCookie(url,theCookie.getValue());
        }
        CookieSyncManager.getInstance().sync();
        cookie=CookieManager.getInstance().getCookie(url);
      }
    }
 catch (    IOException e) {
      Log.w(TAG,"Error setting book search cookie",e);
    }
    client.close();
  }
  return cookie;
}
 

Example 32

From project platform_frameworks_support, under directory /volley/src/com/android/volley/toolbox/.

Source file: HttpClientStack.java

  21 
vote

@Override public HttpResponse performRequest(Request<?> request,Map<String,String> additionalHeaders) throws IOException, AuthFailureError {
  HttpUriRequest httpRequest;
  byte[] postBody=request.getPostBody();
  if (postBody != null) {
    HttpPost postRequest=new HttpPost(request.getUrl());
    postRequest.addHeader("Content-Type",request.getPostBodyContentType());
    HttpEntity entity;
    entity=new ByteArrayEntity(postBody);
    postRequest.setEntity(entity);
    httpRequest=postRequest;
  }
 else {
    httpRequest=new HttpGet(request.getUrl());
  }
  addHeaders(httpRequest,additionalHeaders);
  addHeaders(httpRequest,request.getHeaders());
  onPrepareRequest(httpRequest);
  HttpParams httpParams=httpRequest.getParams();
  int timeoutMs=request.getTimeoutMs();
  HttpConnectionParams.setConnectionTimeout(httpParams,5000);
  HttpConnectionParams.setSoTimeout(httpParams,timeoutMs);
  return mClient.execute(httpRequest);
}
 

Example 33

From project Playlist, under directory /src/com/google/zxing/client/android/book/.

Source file: SearchBookContentsActivity.java

  21 
vote

private static String getCookie(String url){
  String cookie=CookieManager.getInstance().getCookie(url);
  if (cookie == null || cookie.length() == 0) {
    Log.d(TAG,"Book Search cookie was missing or expired");
    HttpUriRequest head=new HttpHead(url);
    AndroidHttpClient client=AndroidHttpClient.newInstance(USER_AGENT);
    try {
      HttpResponse response=client.execute(head);
      if (response.getStatusLine().getStatusCode() == 200) {
        Header[] cookies=response.getHeaders("set-cookie");
        for (        Header theCookie : cookies) {
          CookieManager.getInstance().setCookie(url,theCookie.getValue());
        }
        CookieSyncManager.getInstance().sync();
        cookie=CookieManager.getInstance().getCookie(url);
      }
    }
 catch (    IOException e) {
      Log.w(TAG,"Error setting book search cookie",e);
    }
    client.close();
  }
  return cookie;
}
 

Example 34

From project rest-assured, under directory /rest-assured/src/main/java/com/jayway/restassured/internal/http/.

Source file: AuthConfig.java

  21 
vote

public void process(HttpRequest request,HttpContext ctx) throws HttpException, IOException {
  try {
    HttpUriRequest uriRequest=(HttpUriRequest)request;
    HttpHost host=(HttpHost)ctx.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    final URI requestURI=new URI(host.toURI()).resolve(uriRequest.getURI());
    HttpRequestAdapter oAuthRequest=new HttpRequestAdapter(uriRequest){
      public String getRequestUrl(){
        return requestURI.toString();
      }
    }
;
    this.oauth.sign(oAuthRequest);
  }
 catch (  ClassCastException ex) {
    throw new HttpException("Request must be an instance of HttpUriRequest",ex);
  }
catch (  URISyntaxException ex) {
    throw new HttpException("Error rebuilding request URI",ex);
  }
catch (  OAuthException e) {
    throw new HttpException("OAuth signing error",e);
  }
}
 

Example 35

From project scooter, under directory /source/src/com/scooterframework/common/http/.

Source file: HTTPClient.java

  21 
vote

/** 
 * Sends a HTTP request with parameters.  Please note that the <tt>params</tt> parameter is only useful for  requests using <tt>POST</tt> and <tt>PUT</tt> method.
 * @param method  a HTTP method
 * @param uri     request uri
 * @param params  request parameters
 * @return an HTTPResponse instance
 */
public HTTPResponse fireHttpRequest(String method,String uri,Map<String,String> params){
  if (method == null || "".equals(method))   throw new IllegalArgumentException("method cannot be null or empty.");
  if (uri == null || "".equals(uri))   throw new IllegalArgumentException("uri cannot be null or empty.");
  HttpUriRequest request=null;
  HttpResponse response=null;
  try {
    request=createHttpRequest(method,uri,params);
    response=httpclient.execute(request);
  }
 catch (  Throwable ex) {
    String error=(request != null) ? request.getRequestLine().toString() : uri;
    throw new HTTPRequestError("Failed in request \"" + error + "\"; details: "+ ex.getMessage());
  }
  return new HTTPResponse(response);
}
 

Example 36

From project signedrequest4j, under directory /src/main/java/com/github/seratch/signedrequest4j/.

Source file: SignedRequestApacheHCImpl.java

  21 
vote

@Override public HttpResponse doRequest(String url,HttpMethod method,RequestBody body,String charset) throws IOException {
  HttpClient httpClient=new DefaultHttpClient();
  HttpUriRequest request=getRequest(method,url);
  httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,connectTimeoutMillis);
  httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,readTimeoutMillis);
  httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,USER_AGENT);
  httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,charset);
  for (  String name : headersToOverwrite.keySet()) {
    request.setHeader(name,headersToOverwrite.get(name));
  }
  String oAuthNonce=String.valueOf(new SecureRandom().nextLong());
  Long oAuthTimestamp=System.currentTimeMillis() / 1000;
  String signature=getSignature(url,method,oAuthNonce,oAuthTimestamp);
  String authorizationHeader=getAuthorizationHeader(signature,oAuthNonce,oAuthTimestamp);
  request.setHeader("Authorization",authorizationHeader);
  if (method == HttpMethod.POST) {
    HttpPost postRequest=(HttpPost)request;
    BasicHttpEntity entity=new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(body.getBody()));
    entity.setContentType(body.getContentType());
    postRequest.setEntity(entity);
  }
 else   if (method == HttpMethod.PUT) {
    HttpPut putRequest=(HttpPut)request;
    BasicHttpEntity entity=new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(body.getBody()));
    entity.setContentType(body.getContentType());
    putRequest.setEntity(entity);
  }
  org.apache.http.HttpResponse apacheHCResponse=httpClient.execute(request);
  if (apacheHCResponse.getStatusLine().getStatusCode() >= 400) {
    HttpResponse httpResponse=toReturnValue(apacheHCResponse,charset);
    throw new HttpException(apacheHCResponse.getStatusLine().getReasonPhrase(),httpResponse);
  }
  return toReturnValue(apacheHCResponse,charset);
}
 

Example 37

From project subsonic, under directory /subsonic-android/src/github/daneren2005/dsub/service/.

Source file: RESTMusicService.java

  21 
vote

private void detectRedirect(String originalUrl,Context context,HttpContext httpContext){
  HttpUriRequest request=(HttpUriRequest)httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
  HttpHost host=(HttpHost)httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
  String redirectedUrl;
  if (request.getURI().getScheme() == null) {
    redirectedUrl=host.toURI() + request.getURI();
  }
 else {
    redirectedUrl=request.getURI().toString();
  }
  redirectFrom=originalUrl.substring(0,originalUrl.indexOf("/rest/"));
  redirectTo=redirectedUrl.substring(0,redirectedUrl.indexOf("/rest/"));
  Log.i(TAG,redirectFrom + " redirects to " + redirectTo);
  redirectionLastChecked=System.currentTimeMillis();
  redirectionNetworkType=getCurrentNetworkType(context);
}
 

Example 38

From project Traktoid, under directory /Traktoid/src/com/florianmski/tracktoid/image/.

Source file: Fanart.java

  21 
vote

private synchronized void loadData(URL url,Context c){
  try {
    HttpUriRequest request=new HttpGet(url.toString());
    request.addHeader("Accept-Encoding","gzip");
    res=http.execute(request);
  }
 catch (  IOException e) {
    Log.e("FanartParser","Error loading data",e);
  }
  try {
    InputStream instream=res.getEntity().getContent();
    Header contentEncoding=res.getFirstHeader("Content-Encoding");
    if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip"))     instream=new GZIPInputStream(instream);
    xr.parse(new InputSource(instream));
  }
 catch (  Exception e) {
    Log.e("FanartParser","Error parsing data",e);
  }
}
 

Example 39

From project TransportsRennes, under directory /TransportsBordeaux/src/fr/ybo/transportsbordeaux/tbcapi/.

Source file: Keolis.java

  21 
vote

/** 
 * @param < ObjetKeolis > type d'objet Keolis.
 * @param url           url.
 * @param handler       handler.
 * @return liste d'objets Keolis.
 * @throws TbcErreurReseaux en cas d'erreur r?seau.
 */
private <ObjetKeolis>List<ObjetKeolis> appelKeolis(String url,KeolisHandler<ObjetKeolis> handler) throws ErreurReseau {
  LOG_YBO.debug("Appel d'une API Keolis sur l'url '" + url + '\'');
  long startTime=System.nanoTime() / 1000;
  HttpClient httpClient=HttpUtils.getHttpClient();
  HttpUriRequest httpPost=new HttpPost(url);
  List<ObjetKeolis> answer;
  try {
    HttpResponse reponse=httpClient.execute(httpPost);
    ByteArrayOutputStream ostream=new ByteArrayOutputStream();
    if (reponse == null || reponse.getEntity() == null) {
      throw new ErreurReseau("Erreur lors de la r?cup?ration de la r?ponse http");
    }
    reponse.getEntity().writeTo(ostream);
    String contenu=new String(ostream.toByteArray(),"ISO-8859-1");
    SAXParserFactory factory=SAXParserFactory.newInstance();
    SAXParser parser=factory.newSAXParser();
    parser.parse(new ByteArrayInputStream(contenu.getBytes("UTF-8")),handler);
    answer=handler.getObjets();
  }
 catch (  IOException socketException) {
    throw new ErreurReseau(socketException);
  }
catch (  SAXException saxException) {
    throw new ErreurReseau(saxException);
  }
catch (  ParserConfigurationException exception) {
    throw new KeolisException("Erreur lors de l'appel ? l'API keolis",exception);
  }
  if (answer == null) {
    throw new ErreurReseau("Erreur dans la r?ponse donn?es par Keolis.");
  }
  long elapsedTime=System.nanoTime() / 1000 - startTime;
  LOG_YBO.debug("R?ponse de Keolis en " + elapsedTime + "?s");
  return answer;
}
 

Example 40

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/http/.

Source file: HttpBuilder.java

  19 
vote

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 41

From project android-api_1, under directory /android-lib/src/com/catchnotes/api/.

Source file: VersionedCatchHttpClient.java

  19 
vote

private void addAccessTokenToHttpUriRequest(HttpUriRequest httpUriRequest){
  if (mEncodedAccessToken != null) {
    String query=httpUriRequest.getURI().getQuery();
    if (query == null || query.length() == 0) {
      ((HttpRequestBase)httpUriRequest).setURI(URI.create(httpUriRequest.getURI() + "?" + mEncodedAccessToken));
    }
 else {
      ((HttpRequestBase)httpUriRequest).setURI(URI.create(httpUriRequest.getURI() + "&" + mEncodedAccessToken));
    }
  }
}
 

Example 42

From project android-rackspacecloud, under directory /extensions/apachehc/src/main/java/org/jclouds/http/apachehc/.

Source file: ApacheHCHttpCommandExecutorService.java

  19 
vote

private org.apache.http.HttpResponse executeRequest(HttpUriRequest nativeRequest) throws IOException, ClientProtocolException {
  URI endpoint=URI.create(nativeRequest.getRequestLine().getUri());
  HttpHost host=new HttpHost(endpoint.getHost(),endpoint.getPort(),endpoint.getScheme());
  org.apache.http.HttpResponse nativeResponse=client.execute(host,nativeRequest);
  return nativeResponse;
}
 

Example 43

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/oauth/signpost/commonshttp/.

Source file: HttpRequestAdapter.java

  19 
vote

public HttpRequestAdapter(HttpUriRequest request){
  this.request=request;
  if (request instanceof HttpEntityEnclosingRequest) {
    entity=((HttpEntityEnclosingRequest)request).getEntity();
  }
}
 

Example 44

From project android_packages_apps_Exchange, under directory /src/com/android/exchange/.

Source file: EasResponse.java

  19 
vote

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 45

From project AquaNotesTest, under directory /src/com/google/android/apps/iosched/io/.

Source file: RemoteExecutor.java

  19 
vote

/** 
 * 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 46

From project be.norio.twunch.android, under directory /src/com/google/android/apps/iosched/io/.

Source file: RemoteExecutor.java

  19 
vote

/** 
 * 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 47

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/goodreads/.

Source file: GoodreadsManager.java

  19 
vote

/** 
 * Utility routine called to sign a request and submit it then pass it off to a parser.
 * @author Philip Warner
 * @throws NotAuthorizedException 
 * @throws BookNotFoundException 
 * @throws NetworkException 
 */
public HttpResponse execute(HttpUriRequest request,DefaultHandler requestHandler,boolean requiresSignature) throws ClientProtocolException, IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, NotAuthorizedException, BookNotFoundException, NetworkException {
  HttpClient httpClient=newHttpClient();
  if (requiresSignature) {
    m_consumer.setTokenWithSecret(m_accessToken,m_accessSecret);
    m_consumer.sign(request);
  }
  waitUntilRequestAllowed();
  HttpResponse response;
  try {
    response=httpClient.execute(request);
  }
 catch (  Exception e) {
    throw new NetworkException(e);
  }
  int code=response.getStatusLine().getStatusCode();
  if (code == 200 || code == 201)   parseResponse(response,requestHandler);
 else   if (code == 401) {
    m_hasValidCredentials=false;
    throw new NotAuthorizedException(null);
  }
 else   if (code == 404) {
    throw new BookNotFoundException(null);
  }
 else   throw new RuntimeException("Unexpected status code from API: " + response.getStatusLine().getStatusCode() + "/"+ response.getStatusLine().getReasonPhrase());
  return response;
}
 

Example 48

From project build-info, under directory /build-info-client/src/main/java/org/jfrog/build/client/.

Source file: PreemptiveHttpClient.java

  19 
vote

public HttpResponse execute(HttpUriRequest request) throws IOException {
  if (localContext != null) {
    return httpClient.execute(request,localContext);
  }
 else {
    return httpClient.execute(request);
  }
}
 

Example 49

From project conference-mobile-app, under directory /android-app/src/com/google/android/apps/iosched/io/.

Source file: RemoteExecutor.java

  19 
vote

/** 
 * 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 50

From project dccsched, under directory /src/com/underhilllabs/dccsched/io/.

Source file: RemoteExecutor.java

  19 
vote

/** 
 * 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 51

From project dcnyc10-android, under directory /android/src/com/lullabot/android/apps/iosched/io/.

Source file: RemoteExecutor.java

  19 
vote

/** 
 * 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 52

From project DeskSMS, under directory /DeskSMS/src/com/koushikdutta/desktopsms/.

Source file: StreamUtility.java

  19 
vote

public static String downloadUriAsString(final HttpUriRequest req) throws IOException {
  AndroidHttpClient client=AndroidHttpClient.newInstance("Android");
  try {
    HttpResponse res=client.execute(req);
    return downloadUriAsString(res);
  }
  finally {
    client.close();
  }
}
 

Example 53

From project devoxx-france-android-in-fine, under directory /src/com/infine/android/devoxx/io/json/.

Source file: RemoteJsonExecutor.java

  19 
vote

private void execute(HttpUriRequest request,JsonHandler 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 {
      handler.parseAndApply(input,mResolver);
    }
  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 54

From project droid-fu, under directory /src/test/java/com/github/droidfu/http/.

Source file: BetterHttpTestBase.java

  19 
vote

@SuppressWarnings("unchecked") @Before public void setupHttpClient() throws Exception {
  when(mockResponse.getResponseBody()).thenReturn(new ByteArrayInputStream(responseBody.getBytes()));
  when(mockResponse.getResponseBodyAsBytes()).thenReturn(responseBody.getBytes());
  when(mockResponse.getResponseBodyAsString()).thenReturn(responseBody);
  when(mockResponse.getStatusCode()).thenReturn(200);
  when(httpClientMock.execute(any(HttpUriRequest.class),any(ResponseHandler.class),any(HttpContext.class))).thenReturn(mockResponse);
  BasicHttpParams params=new BasicHttpParams();
  HttpConnectionParams.setSoTimeout(params,BetterHttp.DEFAULT_SOCKET_TIMEOUT);
  when(httpClientMock.getParams()).thenReturn(params);
  BetterHttp.setHttpClient(httpClientMock);
}
 

Example 55

From project droidparts, under directory /extra/src/org/droidparts/http/wrapper/.

Source file: DefaultHttpClientWrapper.java

  19 
vote

public HttpResponse getResponse(HttpUriRequest req) throws HTTPException {
  for (  String name : headers.keySet()) {
    req.setHeader(name,headers.get(name));
  }
  req.setHeader("Accept-Encoding","gzip,deflate");
  try {
    HttpResponse resp=httpClient.execute(req);
    int respCode=resp.getStatusLine().getStatusCode();
    if (respCode >= 400) {
      consumeResponse(resp);
      throw new HTTPException(respCode,null);
    }
    return resp;
  }
 catch (  Exception e) {
    throw new HTTPException(e);
  }
}
 

Example 56

From project gddsched2, under directory /trunk/android/src/com/google/android/apps/iosched2/io/.

Source file: RemoteExecutor.java

  19 
vote

/** 
 * 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 57

From project iosched, under directory /android/src/com/google/android/apps/iosched/io/.

Source file: RemoteExecutor.java

  19 
vote

/** 
 * 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 58

From project iosched2011, under directory /android/src/com/google/android/apps/iosched/io/.

Source file: RemoteExecutor.java

  19 
vote

/** 
 * 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 59

From project iosched_1, under directory /src/com/google/android/apps/iosched/io/.

Source file: RemoteExecutor.java

  19 
vote

/** 
 * 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 60

From project iosched_2, under directory /android/src/com/google/android/apps/iosched/io/.

Source file: RemoteExecutor.java

  19 
vote

/** 
 * 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 61

From project jolokia, under directory /client/java/src/test/java/org/jolokia/client/.

Source file: J4pClientTest.java

  19 
vote

@Test(expectedExceptions=J4pException.class,expectedExceptionsMessageRegExp=".*reading.*response.*") public void throwIOExceptionWhenParsingAnswer() throws IOException, J4pException {
  HttpClient client=createMock(HttpClient.class);
  HttpResponse response=createMock(HttpResponse.class);
  HttpEntity entity=createMock(HttpEntity.class);
  expect(client.execute(EasyMock.<HttpUriRequest>anyObject())).andReturn(response);
  expect(response.getEntity()).andReturn(entity);
  expect(entity.getContentEncoding()).andReturn(null);
  expect(entity.getContent()).andThrow(new IOException());
  entity.consumeContent();
  replay(client,entity,response);
  J4pClient j4p=new J4pClient(TEST_URL,client);
  j4p.execute(TEST_REQUEST);
}
 

Example 62

From project leviathan, under directory /httpclient/src/main/java/ar/com/zauber/leviathan/impl/httpclient/.

Source file: HTTPClientURIFetcher.java

  19 
vote

/** 
 * Actual fetching.
 * @param httpMethod 
 */
private URIFetcherResponse fetchInternal(final URIAndCtx uriAndCtx,final HttpUriRequest httpMethod){
  HttpResponse response=null;
  try {
    final URI uri=uriAndCtx.getURI();
    Validate.notNull(uri,"uri is null");
    response=httpClient.execute(httpMethod);
    Validate.notNull(response);
    final HttpEntity entity=response.getEntity();
    Validate.notNull(entity);
    final InputStream content=entity.getContent();
    Validate.notNull(content);
    byte[] data=IOUtils.toByteArray(content);
    final ResponseMetadata meta=getMetaResponse(uri,response,entity);
    Charset charset;
    try {
      charset=charsetStrategy.getCharset(meta,new ByteArrayInputStream(data));
    }
 catch (    final SkipBytesException e) {
      charset=e.getCharset();
      e.getBytesToSkip();
      data=Arrays.copyOfRange(data,e.getBytesToSkip() - 1,data.length);
    }
    return new InmutableURIFetcherResponse(uriAndCtx,new InmutableURIFetcherHttpResponse(new String(data,charset.displayName()),meta.getStatusCode(),extractHeaders(response),data));
  }
 catch (  final Throwable e) {
    return new InmutableURIFetcherResponse(uriAndCtx,e);
  }
 finally {
    if (response != null) {
      try {
        response.getEntity().consumeContent();
      }
 catch (      final IOException e) {
        return new InmutableURIFetcherResponse(uriAndCtx,e);
      }
    }
  }
}
 

Example 63

From project maven-wagon, under directory /wagon-providers/wagon-http-shared4/src/main/java/org/apache/maven/wagon/shared/http4/.

Source file: AbstractHttpClientWagon.java

  19 
vote

protected HttpResponse execute(HttpUriRequest httpMethod) throws HttpException, IOException {
  setParameters(httpMethod);
  setHeaders(httpMethod);
  client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,getUserAgent(httpMethod));
  ProxyInfo proxyInfo=getProxyInfo(getRepository().getProtocol(),getRepository().getHost());
  if (proxyInfo != null) {
    if (proxyInfo.getUserName() != null && proxyInfo.getPassword() != null) {
      Credentials creds;
      if (proxyInfo.getNtlmHost() != null || proxyInfo.getNtlmDomain() != null) {
        creds=new NTCredentials(proxyInfo.getUserName(),proxyInfo.getPassword(),proxyInfo.getNtlmHost(),proxyInfo.getNtlmDomain());
      }
 else {
        creds=new UsernamePasswordCredentials(proxyInfo.getUserName(),proxyInfo.getPassword());
      }
      Header bs=new BasicScheme().authenticate(creds,httpMethod);
      httpMethod.addHeader("Proxy-Authorization",bs.getValue());
    }
  }
  return client.execute(httpMethod,localContext);
}
 

Example 64

From project memcached-session-manager, under directory /core/src/test/java/de/javakaffee/web/msm/integration/.

Source file: TestUtils.java

  19 
vote

private static HttpResponse executeRequestWithAuth(final DefaultHttpClient client,final HttpUriRequest method,final Credentials credentials) throws IOException, ClientProtocolException {
  client.getCredentialsProvider().setCredentials(AuthScope.ANY,credentials);
  final BasicHttpContext localcontext=new BasicHttpContext();
  final BasicScheme basicAuth=new BasicScheme();
  localcontext.setAttribute("preemptive-auth",basicAuth);
  return client.execute(method,localcontext);
}
 

Example 65

From project milton, under directory /milton/milton-client/src/main/java/com/ettrema/httpclient/.

Source file: Utils.java

  19 
vote

/** 
 * Execute the given request, populate any returned content to the outputstream, and return the status code
 * @param client
 * @param m
 * @param out - may be null
 * @return
 * @throws IOException
 */
public static int executeHttpWithStatus(HttpClient client,HttpUriRequest m,OutputStream out) throws IOException {
  HttpResult result=executeHttpWithResult(client,m,out);
  if (log.isTraceEnabled()) {
    for (    String key : result.getHeaders().keySet()) {
      log.trace(" header: " + key + " = "+ result.getHeaders().get(key));
    }
  }
  return result.getStatusCode();
}
 

Example 66

From project milton2, under directory /milton-client/src/main/java/io/milton/httpclient/.

Source file: Utils.java

  19 
vote

public static HttpResult executeHttpWithResult(HttpClient client,HttpUriRequest m,OutputStream out) throws IOException {
  HttpResponse resp=client.execute(m);
  HttpEntity entity=resp.getEntity();
  if (entity != null) {
    InputStream in=null;
    try {
      in=entity.getContent();
      if (out != null) {
        IOUtils.copy(in,out);
      }
    }
  finally {
      IOUtils.closeQuietly(in);
    }
  }
  Map<String,String> mapOfHeaders=new HashMap<String,String>();
  Header[] respHeaders=resp.getAllHeaders();
  for (  Header h : respHeaders) {
    mapOfHeaders.put(h.getName(),h.getValue());
  }
  HttpResult result=new HttpResult(resp.getStatusLine().getStatusCode(),mapOfHeaders);
  return result;
}
 

Example 67

From project nuxeo-android, under directory /nuxeo-automation-thin-client/src/main/java/org/nuxeo/ecm/automation/client/jaxrs/impl/.

Source file: HttpConnector.java

  19 
vote

protected Object execute(Request request,HttpUriRequest httpReq,String cacheKey) throws Exception {
  for (  Map.Entry<String,String> entry : request.entrySet()) {
    httpReq.setHeader(entry.getKey(),entry.getValue());
  }
  HttpResponse resp=http.execute(httpReq,ctx);
  HttpEntity entity=resp.getEntity();
  int status=resp.getStatusLine().getStatusCode();
  if (entity == null) {
    if (status < 400) {
      return null;
    }
    throw new RemoteException(status,"ServerError","Server Error",null);
  }
  Header ctypeHeader=entity.getContentType();
  if (ctypeHeader == null) {
    if (status != 200) {
      throw new RemoteException(status,"ServerError","Server Error",null);
    }
    return null;
  }
  String ctype=ctypeHeader.getValue().toLowerCase();
  String disp=null;
  Header[] hdisp=resp.getHeaders("Content-Disposition");
  if (hdisp != null && hdisp.length > 0) {
    disp=hdisp[0].getValue();
  }
  InputStream is=entity.getContent();
  if (cacheKey != null && cacheManager != null && status == 200) {
    is=cacheManager.addToCache(cacheKey,new CacheEntry(ctype,disp,is));
  }
  return request.handleResult(status,ctype,disp,is);
}
 

Example 68

From project OpenBike, under directory /src/fr/openbike/android/io/.

Source file: RemoteExecutor.java

  19 
vote

public Object execute(HttpUriRequest request,JSONHandler handler,Context context) 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();
    Object result=null;
    try {
      result=handler.parse(new JSONObject(ParserUtils.getString(input)),OpenBikeDBAdapter.getInstance(context));
      if (input != null)       input.close();
      return result;
    }
 catch (    JSONException e) {
      if (input != null)       input.close();
      throw new HandlerException("Malformed response for " + request.getRequestLine(),e);
    }
  }
 catch (  HandlerException e) {
    throw e;
  }
catch (  IOException e) {
    throw new HandlerException("Problem reading remote response for " + request.getRequestLine(),e);
  }
}
 

Example 69

From project OpenMEAP, under directory /java-shared/openmeap-shared-jdk5/src/com/openmeap/http/.

Source file: HttpRequestExecuterImpl.java

  19 
vote

protected HttpResponse execute(HttpUriRequest request) throws IllegalStateException, IOException {
  org.apache.http.HttpResponse clientResponse=httpClient.execute(request);
  HttpResponseImpl returnResponse=new HttpResponseImpl();
  returnResponse.setResponseBody(clientResponse.getEntity().getContent());
  returnResponse.setContentLength(clientResponse.getEntity().getContentLength());
  returnResponse.setStatusCode(clientResponse.getStatusLine().getStatusCode());
  List<HttpHeader> headers=new ArrayList<HttpHeader>();
  for (  Header header : clientResponse.getAllHeaders()) {
    headers.add(new HttpHeader(header.getName(),header.getValue()));
  }
  returnResponse.setHeaders(headers.toArray(new HttpHeader[headers.size()]));
  return returnResponse;
}
 

Example 70

From project platform_external_apache-http, under directory /src/org/apache/http/impl/client/.

Source file: AbstractHttpClient.java

  19 
vote

/** 
 * Maps to  {@link HttpClient#execute(HttpHost,HttpRequest,HttpContext) execute(target, request, context)}. The target is determined from the URI of the request.
 * @param request   the request to execute
 * @param context   the request-specific execution context,or <code>null</code> to use a default context
 */
public final HttpResponse execute(HttpUriRequest request,HttpContext context) throws IOException, ClientProtocolException {
  if (request == null) {
    throw new IllegalArgumentException("Request must not be null.");
  }
  return execute(determineTarget(request),request,context);
}
 

Example 71

From project rain-workload-toolkit, under directory /src/radlab/rain/util/.

Source file: HttpTransport.java

  19 
vote

/** 
 * Executes an HTTP GET request.
 * @param httpGet       The HTTP GET request to execute.
 * @param headers       The headers to add to the request.
 * @return              The content of the response.
 * @throws IOException
 */
public StringBuilder fetch(HttpGet httpGet,Map<String,String> headers) throws IOException {
  if (headers != null) {
    HttpTransport.setHeaders(httpGet,headers);
  }
  return this.fetch((HttpUriRequest)httpGet);
}
 

Example 72

From project restfulie-java, under directory /client/src/main/java/br/com/caelum/restfulie/http/apache/.

Source file: ApacheDispatcher.java

  19 
vote

private HttpUriRequest verbFor(String method,URI uri){
  method=method.toUpperCase();
  if (method.equals("GET")) {
    return new HttpGet(uri);
  }
 else   if (method.equals("PUT")) {
    return new HttpPut(uri);
  }
 else   if (method.equals("POST")) {
    return new HttpPost(uri);
  }
 else   if (method.equals("DELETE")) {
    return new HttpDelete(uri);
  }
 else   if (method.equals("TRACE")) {
    return new HttpTrace(uri);
  }
 else   if (method.equals("OPTIONS")) {
    return new HttpOptions(uri);
  }
 else   if (method.equals("HEAD")) {
    return new HttpHead(uri);
  }
  throw new RestfulieException("You can not " + method + " to "+ uri+ ", there is no such verb in the apache http API.");
}
 

Example 73

From project riak-java-client, under directory /src/test/java/com/basho/riak/client/http/util/.

Source file: TestClientHelper.java

  19 
vote

@Test public void store_will_use_post_when_no_key_is_provided() throws ClientProtocolException, IOException {
  when(mockHttpClient.execute(any(HttpUriRequest.class))).thenReturn(mockHttpResponse);
  RiakObject objectWithNoKey=new RiakObject(bucket,null);
  impl.store(objectWithNoKey,meta);
  ArgumentCaptor<HttpRequestBase> httpRequestBaseCaptor=ArgumentCaptor.forClass(HttpRequestBase.class);
  verify(mockHttpClient).execute(httpRequestBaseCaptor.capture());
  HttpRequestBase requestObject=httpRequestBaseCaptor.getValue();
  assertEquals("Store without key needs to be POST for Riak to understand.","POST",requestObject.getMethod());
}
 

Example 74

From project saldo, under directory /src/com/adrup/http/.

Source file: HttpHelper.java

  19 
vote

private static String doRequest(HttpClient httpClient,HttpUriRequest request,String url,HttpContext context,boolean readResponse) throws IOException, HttpException {
  if (httpClient == null)   httpClient=new DefaultHttpClient();
  ResponseHandler<String> responseHandler=new BasicResponseHandler();
  String response=httpClient.execute(request,responseHandler,context);
  return response;
}
 

Example 75

From project signpost, under directory /signpost-commonshttp4/src/main/java/oauth/signpost/commonshttp/.

Source file: HttpRequestAdapter.java

  19 
vote

public HttpRequestAdapter(org.apache.http.client.methods.HttpUriRequest request){
  this.request=request;
  if (request instanceof HttpEntityEnclosingRequest) {
    entity=((HttpEntityEnclosingRequest)request).getEntity();
  }
}
 

Example 76

From project sonet, under directory /core/src/com/piusvelte/sonet/core/.

Source file: SonetOAuth.java

  19 
vote

public HttpUriRequest getSignedRequest(HttpUriRequest httpRequest){
  try {
    mOAuthConsumer.sign(httpRequest);
    return httpRequest;
  }
 catch (  OAuthMessageSignerException e) {
    Log.e(TAG,e.toString());
  }
catch (  OAuthExpectationFailedException e) {
    Log.e(TAG,e.toString());
  }
catch (  OAuthCommunicationException e) {
    Log.e(TAG,e.toString());
  }
  return null;
}
 

Example 77

From project spark, under directory /spark-http-client/src/main/java/spark/protocol/.

Source file: ProtocolCommand.java

  19 
vote

/** 
 * Sets the currently executing request. 
 */
void setRequest(HttpUriRequest request){
  requestLock.lock();
  try {
    if (this.request != null) {
      throw new SparqlException("Command is already executing a request.");
    }
    this.request=request;
  }
  finally {
    requestLock.unlock();
  }
}
 

Example 78

From project sparsemapcontent, under directory /extensions/integration/src/main/java/uk/co/tfd/sm/integration/.

Source file: HttpTestUtils.java

  19 
vote

public JsonElement execute(HttpUriRequest post,int code,String contentType,boolean echo) throws ClientProtocolException, IOException {
  post.setHeader("Referer","/integrationtests");
  HttpResponse response=defaultHttpClient.execute(post);
  Assert.assertEquals(code,response.getStatusLine().getStatusCode());
  if (code >= 200 && code < 300) {
    Assert.assertEquals(contentType,response.getHeaders("Content-Type")[0].getValue());
    String jsonBody=IOUtils.toString(response.getEntity().getContent());
    if (echo) {
      LOGGER.info("Got {} ",jsonBody);
    }
    JsonParser parser=new JsonParser();
    return parser.parse(jsonBody);
  }
  IOUtils.toString(response.getEntity().getContent());
  return null;
}
 

Example 79

From project spliffy, under directory /spliffy-sync/src/main/java/org/spliffy/sync/.

Source file: HttpUtils.java

  19 
vote

public static int executeHttpWithStatus(org.apache.http.client.HttpClient client,HttpUriRequest m,OutputStream out) throws IOException {
  HttpResponse resp=client.execute(m);
  HttpEntity entity=resp.getEntity();
  if (entity != null) {
    InputStream in=null;
    try {
      in=entity.getContent();
      if (out != null) {
        IOUtils.copy(in,out);
      }
    }
  finally {
      IOUtils.closeQuietly(in);
    }
  }
  return resp.getStatusLine().getStatusCode();
}
 

Example 80

From project spring-android, under directory /spring-android-rest-template/src/main/java/org/springframework/http/client/.

Source file: HttpComponentsClientHttpRequestFactory.java

  19 
vote

/** 
 * Create a HttpComponents HttpUriRequest object for the given HTTP method and URI specification.
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the HttpComponents HttpUriRequest object
 */
protected HttpUriRequest createHttpRequest(HttpMethod httpMethod,URI uri){
switch (httpMethod) {
case GET:
    return new HttpGet(uri);
case DELETE:
  return new HttpDelete(uri);
case HEAD:
return new HttpHead(uri);
case OPTIONS:
return new HttpOptions(uri);
case POST:
return new HttpPost(uri);
case PUT:
return new HttpPut(uri);
case TRACE:
return new HttpTrace(uri);
default :
throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
}
}
 

Example 81

From project spring-social, under directory /spring-social-core/src/main/java/org/springframework/social/support/.

Source file: ClientHttpRequestFactorySelector.java

  19 
vote

public static ClientHttpRequestFactory createRequestFactory(String proxyHost,int proxyPort){
  HttpComponentsClientHttpRequestFactory requestFactory=new HttpComponentsClientHttpRequestFactory(){
    @Override protected void postProcessHttpRequest(    HttpUriRequest request){
      HttpProtocolParams.setUseExpectContinue(request.getParams(),false);
    }
  }
;
  if (proxyHost != null) {
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpHost proxy=new HttpHost(proxyHost,proxyPort);
    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
    requestFactory.setHttpClient(httpClient);
  }
  return requestFactory;
}
 

Example 82

From project teamcity-nuget-support, under directory /nuget-server/src/jetbrains/buildServer/nuget/server/feed/reader/impl/.

Source file: UrlResolverImpl.java

  19 
vote

@Nullable public String getRedirectedUrl(@NotNull HttpUriRequest request,@NotNull HttpResponse response) throws IOException {
  try {
    final RedirectStrategy redirectStrategy=getRedirectStrategy();
    if (!redirectStrategy.isRedirected(request,response,createContext())) {
      return null;
    }
    return redirectStrategy.getRedirect(request,response,createContext()).getURI().toString();
  }
 catch (  ProtocolException e) {
    return null;
  }
}