Search Results

Search found 335 results on 14 pages for 'httpclient'.

Page 5/14 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • What version of Apache HTTP Client is bundled in Android 1.6?

    - by Benju
    I want to have a seperate project that runs my server communication code in a normal JVM for the purposes of integration testing. This code uses these libraries which are build into the Android Framework... http://developer.android.com/reference/org/apache/http/client/package-summary.html Does anybody know what version of Apache HTTP Client this is supposed to be? I want to run it without the Android tests which are painfully slow.

    Read the article

  • Trying to run multiple HTTP requests in parallel, but being limited by Windows (registry)

    - by Nailuj
    I'm developing an application (winforms C# .NET 4.0) where I access a lookup functionality from a 3rd party through a simple HTTP request. I call an url with a parameter, and in return I get a small string with the result of the lookup. Simple enough. The challenge is however, that I have to do lots of these lookups (a couple of thousands), and I would like to limit the time needed. Therefore I would like to run requests in parallel (say 10-20). I use a ThreadPool to do this, and the short version of my code looks like this: public void startAsyncLookup(Action<LookupResult> returnLookupResult) { this.returnLookupResult = returnLookupResult; foreach (string number in numbersToLookup) { ThreadPool.QueueUserWorkItem(lookupNumber, number); } } public void lookupNumber(Object threadContext) { string numberToLookup = (string)threadContext; string url = @"http://some.url.com/?number=" + numberToLookup; WebClient webClient = new WebClient(); Stream responseData = webClient.OpenRead(url); LookupResult lookupResult = parseLookupResult(responseData); returnLookupResult(lookupResult); } I fill up numbersToLookup (a List<String>) from another place, call startAsyncLookup and provide it with a call-back function returnLookupResult to return each result. This works, but I found that I'm not getting the throughput I want. Initially I thought it might be the 3rd party having a poor system on their end, but I excluded this by trying to run the same code from two different machines at the same time. Each of the two took as long as one did alone, so I could rule out that one. A colleague then tipped me that this might be a limitation in Windows. I googled a bit, and found amongst others this post saying that by default Windows limits the number of simultaneous request to the same web server to 4 for HTTP 1.0 and to 2 for HTTP 1.1 (for HTTP 1.1 this is actually according to the specification (RFC2068)). The same post referred to above also provided a way to increase these limits. By adding two registry values to [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings] (MaxConnectionsPerServer and MaxConnectionsPer1_0Server), I could control this myself. So, I tried this (sat both to 20), restarted my computer, and tried to run my program again. Sadly though, it didn't seem to help any. I also kept an eye on the Resource Monitor (see screen shot) while running my batch lookup, and I noticed that my application (the one with the title blacked out) still only was using two TCP connections. So, the question is, why isn't this working? Is the post I linked to using the wrong registry values? Is this perhaps not possible to "hack" in Windows any longer (I'm on Windows 7)? Any ideas would be highly appreciated :) And just in case anyone should wonder, I have also tried with different settings for MaxThreads on ThreadPool (everyting from 10 to 100), and this didn't seem to affect my throughput at all, so the problem shouldn't be there either.

    Read the article

  • Solr adding document cycle & wait on response issue

    - by user1585896
    I am trying to send http post request to Solr for adding 50000 documents (all individual request one after another in while loop). I am using DefaultHttpClient in java to connect to Solr and when I use execute method on my HttpPost Solr takes 3 to 4 ms to response. I have commit=false, autoCommit=false, autoSoftCommit=false. My question is why it takes that much time to response and why cycle it follows to add new document. Basically I want to send add request but do not want to commit to see how many request can Solr handle without doing any kind of commits(without having to do any disk access). My guess is with above parameter tuned off I should be hitting Solr about 10000 times every second, but my result is 300 times a second. I am generating random data to add in my code.

    Read the article

  • Android HTTPClient not working inspite of giving permissions in manifest file.

    - by primal
    Hi, I was trying http-cleint tutorials from svn.apache.org. While running the application I am getting the following error in console. [2010-04-30 09:26:36 - HalloAndroid] ActivityManager: java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.org.example/.HalloAndroid } from null (pid=-1, uid=-1) requires android.permission.INTERNET I have added android.permission.INTERNET in AndroidManifest.xml. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.org.example" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".HalloAndroid" android:label="@string/app_name" android:permission="android.permission.INTERNET"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET"></uses-permission> </manifest> The java code in HalloAndroid.java is as follows HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget2 = new HttpGet("http://google.com/"); HttpResponse response2 = null; try { response2 = httpclient.execute(httpget2); } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } HttpEntity entity = response2.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len != -1 && len < 2048) { try { Log.d(TAG, EntityUtils.toString(entity)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // Stream content out } Any help is much appreciated.

    Read the article

  • problem to create session of facebook login

    - by khoyendra
    import com.facebook.api.FacebookRestClient; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpClientParams; public class FaceLogin { public FaceLogin(){ getUserID("xxxxxx", "xxxxxx"); } private static void getUserID(String email, String password){ String session = null; try { HttpClient http = new HttpClient(); http.setParams(new HttpClientParams()); http.setState(new HttpState()); String api_key = "API KEY"; String secret = "SECRETS"; FacebookRestClient client = new FacebookRestClient(api_key, secret); client.setIsDesktop(true); String token = client.auth_createToken(); final String loginId = "http://www.facebook.com/login.php"; GetMethod get = new GetMethod(loginId + "?api_key=" + api_key + "&v=1.0&auth_token=" +token); System.out.println("Get="+get); http.executeMethod(get); PostMethod post = new PostMethod(loginId); post.addParameter(new NameValuePair("api_key", api_key)); post.addParameter(new NameValuePair("v", "1.0")); post.addParameter(new NameValuePair("auth_token", token)); post.addParameter(new NameValuePair("fbconnect","true")); post.addParameter(new NameValuePair("return_session","true")); post.addParameter(new NameValuePair("session_key_only","true")); post.addParameter(new NameValuePair("req_perms","read_stream,publish_stream")); post.addParameter(new NameValuePair("lsd","8HYdi")); post.addParameter(new NameValuePair("locale","en_US")); post.addParameter(new NameValuePair("persistent","1")); post.addParameter(new NameValuePair("email", email)); post.addParameter(new NameValuePair("pass", password)); System.out.println("Token ="+token); int postStatus = http.executeMethod(post); System.out.println("Response : " + postStatus); session = client.auth_getSession(token); // Here I am getting error System.out.println("Session string: " + session); long userid = client.users_getLoggedInUser(); System.out.println("User Id is : " + userid); } catch (Exception e) { e.printStackTrace(); } } public static void main(String k[]) { FacebookLogin facebookLoginObj=new FacebookLogin(); } } here i have to find some error when i create session error is run: Get=org.apache.commons.httpclient.methods.GetMethod@17ec9f7 Token =0c578e0692ae04327cd29a4beede48e3 Jun 8, 2010 7:04:48 PM org.apache.commons.httpclient.HttpMethodBase processResponseHeaders WARNING: Cookie rejected: "$Version=0; $Domain=deleted; $Path=/; $Domain=.facebook.com". Cookie name may not start with $ Response : 200 Jun 8, 2010 7:04:48 PM org.apache.commons.httpclient.HttpMethodBase processResponseHeaders WARNING: Cookie rejected: "$Version=0; $Path=deleted; $Path=/; $Domain=.facebook.com". Cookie name may not start with $ Facebook returns error code 100 - v -> 1.0 - auth_token -> 0c578e0692ae04327cd29a4beede48e3 - method -> facebook.auth.getSession com.facebook.api.FacebookException: Invalid parameter - call_id -> 1276004088734 - api_key -> f7cb1e48c383ef599da9021fc4dec322 - sig -> 8b7f0a5394b25551ab3cf1487ac0da00 at com.facebook.api.FacebookRestClient.callMethod(FacebookRestClient.java:828) at com.facebook.api.FacebookRestClient.callMethod(FacebookRestClient.java:606) at com.facebook.api.FacebookRestClient.callMethod(FacebookRestClient.java:606) at com.facebook.api.FacebookRestClient.auth_getSession(FacebookRestClient.java:1891) at facebookcrawler.FacebookLogin.getUserID(FacebookLogin.java:81) at facebookcrawler.FacebookLogin.<init>(FacebookLogin.java:24) at facebookcrawler.FaceLogin.main(FaceLogin.java:80) BUILD SUCCESSFUL (total time: 7 seconds)

    Read the article

  • Logs are filling up with httpclient.wire.content dumps. How can I turn it off?

    - by ?????
    My catalina logs are filling up with gobs of statements like: /logs/catalina.out:2010-05-05 02:57:19,611 [Thread-19] DEBUG httpclient.wire.content - >> "[0x4] [0xc][0xd9][0xf4][0xa2]MA[0xed][0xc2][0x93][0x1b][0x15][0xfe],[0xe]h[0xb0][0x1f][0xff][0xd6][0xfb] [0x8f]O[0xd4][0xc4]0[0xab][0x80][0xe8][0xe4][0xf2][\r]I&[0xaa][0xd2]BQ[0xdb](zq[0xcd]ac[0xa8] on and on forever. I searched every config file in both tomcat and apache for the statements that purportedly turn this on as described here: http://hc.apache.org/httpclient-3.x/logging.html And I don't see where this logging as been enabled. No other .war I deployed does this. The log4j configuration block in the app isn't doing it. Any ideas? I'm using an S3 library for grails that may be the source for these. However when I run this application on my development machine (in both develop and deploy configs), I'm not seeing it.

    Read the article

  • WSDLException : An error occurred trying to resolve schema referenced at ...

    - by Stefano
    Hello i'm trying to generate a proxy class from a local wsdl file with eclipse Galileo and axis 2 1.4 on windows xp . My problem is that i get an error due to an imported schema inside the wsdl . The line tha troubles me is : <xsd:import namespace="http://www.w3.org/2005/05/xmlmime" schemaLocation="http://www.w3.org/2005/05/xmlmime"/> i've tried to run the wsdl2java following command: wsdl2java.bat -uri SOAService.wsdl -o D:\temp p test -d xmlbeans -a -s -ns2p -uw and i get the following exception : Exception in thread "main" org.apache.axis2.wsdl.codegen.CodeGenerationException : Error parsing WSDL at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.(CodeGenerat ionEngine.java:156) at org.apache.axis2.wsdl.WSDL2Code.main(WSDL2Code.java:35) at org.apache.axis2.wsdl.WSDL2Java.main(WSDL2Java.java:24) Caused by: javax.wsdl.WSDLException: WSDLException (at /wsdl:definitions/wsdl:ty pes/xsd:schema): faultCode=OTHER_ERROR: An error occurred trying to resolve sche ma referenced at 'http://www.w3.org/2005/05/xmlmime', relative to 'file:/D:/Prog rammi/axis2-1.4/bin/SOAService.wsdl'.: java.net.ConnectException: Connection tim ed out: connect at com.ibm.wsdl.xml.WSDLReaderImpl.parseSchema(Unknown Source) at com.ibm.wsdl.xml.WSDLReaderImpl.parseSchema(Unknown Source) at com.ibm.wsdl.xml.WSDLReaderImpl.parseTypes(Unknown Source) at com.ibm.wsdl.xml.WSDLReaderImpl.parseDefinitions(Unknown Source) at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(Unknown Source) at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(Unknown Source) at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(Unknown Source) at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(Unknown Source) at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(Unknown Source) at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.readInTheWSDLFile( CodeGenerationEngine.java:288) at org.apache.axis2.wsdl.codegen.CodeGenerationEngine.(CodeGenerat ionEngine.java:111) ... 2 more Caused by: java.net.ConnectException: Connection timed out: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.Socket.connect(Socket.java:520) at java.net.Socket.connect(Socket.java:470) at sun.net.NetworkClient.doConnect(NetworkClient.java:157) at sun.net.www.http.HttpClient.openServer(HttpClient.java:388) at sun.net.www.http.HttpClient.openServer(HttpClient.java:523) at sun.net.www.http.HttpClient.(HttpClient.java:231) at sun.net.www.http.HttpClient.New(HttpClient.java:304) at sun.net.www.http.HttpClient.New(HttpClient.java:321) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLC onnection.java:813) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConne ction.java:765) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection .java:690) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLCon nection.java:934) at java.net.URL.openStream(URL.java:1007) at com.ibm.wsdl.util.StringUtils.getContentAsInputStream(Unknown Source) i suspect it's due to the system proxy which doesn't let retrieve the xsd to the wsdl2java tool. In fact i can download the file from the browser without problems. There's an option to specify a proxy to wsdl2java or someone has resolved this issue ? For the moment i've downloaded the xsd, added it to the project and changed the wsdl to include the relative file (instead of the remote one) , but i'd prefer to avoid this , because the file is a third party service wsdl. thank you in advance for any hint Stefano

    Read the article

  • while creating archetype getting following error

    - by munna
    D:\Training\workspace\vppsourcemvn archetype:generate -B -DarchetypeGroupId=org .appfuse.archetypes -DarchetypeArtifactId=appfuse-modular-struts-archetype -Darc hetypeVersion=2.1.0-M1 -DgroupId=com.vmware -DartifactId=vpp [INFO] Scanning for projects... [INFO] Searching repository for plugin with prefix: 'archetype'. [INFO] ------------------------------------------------------------------------ [INFO] Building Maven Default Project [INFO] task-segment: [archetype:generate] (aggregator-style) [INFO] ------------------------------------------------------------------------ [INFO] Preparing archetype:generate [INFO] No goals needed for project - skipping [INFO] [archetype:generate {execution: default-cli}] [INFO] Generating project in Batch mode [WARNING] Error reading archetype catalog http://repo1.maven.org/maven2 org.apache.maven.wagon.TransferFailedException: Error transferring file: Connect ion timed out: connect at org.apache.maven.wagon.providers.http.LightweightHttpWagon.fillInputD ata(LightweightHttpWagon.java:143) at org.apache.maven.wagon.StreamWagon.getInputStream(StreamWagon.java:11 6) at org.apache.maven.wagon.StreamWagon.getIfNewer(StreamWagon.java:88) at org.apache.maven.wagon.StreamWagon.get(StreamWagon.java:61) at org.apache.maven.archetype.source.RemoteCatalogArchetypeDataSource.ge tArchetypeCatalog(RemoteCatalogArchetypeDataSource.java:97) at org.apache.maven.archetype.DefaultArchetypeManager.getRemoteCatalog(D efaultArchetypeManager.java:195) at org.apache.maven.archetype.DefaultArchetypeManager.getRemoteCatalog(D efaultArchetypeManager.java:184) at org.apache.maven.archetype.ui.DefaultArchetypeSelector.getArchetypesB yCatalog(DefaultArchetypeSelector.java:278) at org.apache.maven.archetype.ui.DefaultArchetypeSelector.selectArchetyp e(DefaultArchetypeSelector.java:69) at org.apache.maven.archetype.mojos.CreateProjectFromArchetypeMojo.execu te(CreateProjectFromArchetypeMojo.java:186) at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPlugi nManager.java:490) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(Defa ultLifecycleExecutor.java:694) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandalone Goal(DefaultLifecycleExecutor.java:569) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(Defau ltLifecycleExecutor.java:539) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHan dleFailures(DefaultLifecycleExecutor.java:387) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegmen ts(DefaultLifecycleExecutor.java:284) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLi fecycleExecutor.java:180) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138) at org.apache.maven.cli.MavenCli.main(MavenCli.java:362) at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:6 0) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces sorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) at org.codehaus.classworlds.Launcher.main(Launcher.java:375) Caused by: java.net.ConnectException: Connection timed out: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:529) at java.net.Socket.connect(Socket.java:478) at sun.net.NetworkClient.doConnect(NetworkClient.java:163) at sun.net.www.http.HttpClient.openServer(HttpClient.java:394) at sun.net.www.http.HttpClient.openServer(HttpClient.java:529) at sun.net.www.http.HttpClient.(HttpClient.java:233) at sun.net.www.http.HttpClient.New(HttpClient.java:306) at sun.net.www.http.HttpClient.New(HttpClient.java:323) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLC onnection.java:860) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConne ction.java:801) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection .java:726) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLCon nection.java:1049) at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373 ) at org.apache.maven.wagon.providers.http.LightweightHttpWagon.fillInputD ata(LightweightHttpWagon.java:115) ... 28 more [WARNING] No archetype found in Remote catalog. Defaulting to internal Catalog [INFO] ------------------------------------------------------------------------ [ERROR] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] [INFO] ------------------------------------------------------------------------ [INFO] For more information, run Maven with the -e switch [INFO] ------------------------------------------------------------------------ [INFO] Total time: 46 seconds [INFO] Finished at: Wed Jun 09 16:11:07 IST 2010 [INFO] Final Memory: 11M/28M [INFO] ------------------------------------------------------------------------

    Read the article

  • Integrate openid4java to GWT Project

    - by Slyker
    Hi, I created an GWT project in eclipse. Now I tried to implement openId with using the openid4java library. I imported the .jar files via properties--java build path: openid4java-0.9.5.jar lib/*.jar In addition I copied the .jar files into the war/WEB-INF/lib directory. The problem at hand comes up when I call the authenticate() method. Then I get a: HTTP ERROR 500 Problem accessing /openid/openid. Reason: access denied (java.lang.RuntimePermission modifyThreadGroup)Caused by:java.security.AccessControlException: access denied (java.lang.RuntimePermission modifyThreadGroup) at java.security.AccessControlContext.checkPermission(Unknown Source) at java.security.AccessController.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPermission(Unknown Source) at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkPermission(DevAppServerFactory.java:166) at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkAccess(DevAppServerFactory.java:191) at java.lang.ThreadGroup.checkAccess(Unknown Source) at java.lang.Thread.init(Unknown Source) at java.lang.Thread.<init>(Unknown Source) at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$ReferenceQueueThread.<init>(MultiThreadedHttpConnectionManager.java:1039) at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.storeReferenceToConnection(MultiThreadedHttpConnectionManager.java:164) at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.access$900(MultiThreadedHttpConnectionManager.java:64) at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$ConnectionPool.createConnection(MultiThreadedHttpConnectionManager.java:750) at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.doGetConnection(MultiThreadedHttpConnectionManager.java:469) at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.getConnectionWithTimeout(MultiThreadedHttpConnectionManager.java:394) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:152) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324) at org.openid4java.util.HttpCache.head(HttpCache.java:296) at org.openid4java.discovery.yadis.YadisResolver.retrieveXrdsLocation(YadisResolver.java:360) at org.openid4java.discovery.yadis.YadisResolver.discover(YadisResolver.java:229) at org.openid4java.discovery.yadis.YadisResolver.discover(YadisResolver.java:221) at org.openid4java.discovery.yadis.YadisResolver.discover(YadisResolver.java:179) at org.openid4java.discovery.Discovery.discover(Discovery.java:134) at org.openid4java.discovery.Discovery.discover(Discovery.java:114) at org.openid4java.consumer.ConsumerManager.discover(ConsumerManager.java:527) at auth.openid.server.OpenIDServlet.authenticate(OpenIDServlet.java:138) at auth.openid.server.OpenIDServlet.doGet(OpenIDServlet.java:101) at javax.servlet.http.HttpServlet.service(HttpServlet.java:693) at javax.servlet.http.HttpServlet.service(HttpServlet.java:806) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166) at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:51) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:122) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418) at com.google.apphosting.utils.jetty.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:70) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:349) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:326) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) Here my servlet source: import com.google.gwt.user.client.rpc.RemoteService; import org.openid4java.OpenIDException; import org.openid4java.consumer.ConsumerException; import org.openid4java.consumer.ConsumerManager; import org.openid4java.consumer.VerificationResult; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.discovery.Identifier; import org.openid4java.message.AuthRequest; import org.openid4java.message.ParameterList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.MessageFormat; import java.util.List; public final class OpenIDServlet extends HttpServlet implements RemoteService { private final ConsumerManager manager; public OpenIDServlet() { try { manager = new ConsumerManager(); } catch (ConsumerException e) { throw new RuntimeException("Error creating consumer manager", e); } } ... private void authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { final String loginString = request.getParameter(nameParameter); try { // perform discovery on the user-supplied identifier List discoveries = manager.discover(loginString); // attempt to associate with the OpenID provider // and retrieve one service endpoint for authentication DiscoveryInformation discovered = manager.associate(discoveries); // obtain a AuthRequest message to be sent to the OpenID provider AuthRequest authReq = manager.authenticate(discovered, "openid", null); // redirect to OpenID for authentication response.sendRedirect(authReq.getDestinationUrl(true)); } catch (OpenIDException e) { throw new ServletException("Login string probably caused an error. loginString = " + loginString, e); } } My question now is: What could be my fault? Did I make any mistakes in importing the openid4java library? (which?) All other methods in the servlet which do not use the openid4java implementation work fine. Thanks, Andreas

    Read the article

  • XML over HTTP with JMS and Spring

    - by Will Sumekar
    I have a legacy HTTP server where I need to send an XML file over HTTP request (POST) using Java (not browser) and the server will respond with another XML in its HTTP response. It is similar to Web Service but there's no WSDL and I have to follow the existing XML structure to construct my XML to be sent. I have done a research and found an example that matches my requirement here. The example uses HttpClient from Apache Commons. (There are also other examples I found but they use java.net networking package (like URLConnection) which is tedious so I don't want to use them). But it's also my requirement to use Spring and JMS. I know from Spring's reference that it's possible to combine HttpClient, JMS and Spring. My question is, how? Note that it's NOT in my requirement to use HttpClient. If you have a better suggestion, I'm welcome. Appreciate it. For your reference, here's the XML-over-HTTP example I've been talking about: /* * $Header: * $Revision$ * $Date$ * ==================================================================== * * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * [Additional notices, if required by prior licensing conditions] * */ import java.io.File; import java.io.FileInputStream; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; /** * * This is a sample application that demonstrates * how to use the Jakarta HttpClient API. * * This application sends an XML document * to a remote web server using HTTP POST * * @author Sean C. Sullivan * @author Ortwin Glück * @author Oleg Kalnichevski */ public class PostXML { /** * * Usage: * java PostXML http://mywebserver:80/ c:\foo.xml * * @param args command line arguments * Argument 0 is a URL to a web server * Argument 1 is a local filename * */ public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println( "Usage: java -classpath <classpath> [-Dorg.apache.commons."+ "logging.simplelog.defaultlog=<loglevel>]" + " PostXML <url> <filename>]"); System.out.println("<classpath> - must contain the "+ "commons-httpclient.jar and commons-logging.jar"); System.out.println("<loglevel> - one of error, "+ "warn, info, debug, trace"); System.out.println("<url> - the URL to post the file to"); System.out.println("<filename> - file to post to the URL"); System.out.println(); System.exit(1); } // Get target URL String strURL = args[0]; // Get file to be posted String strXMLFilename = args[1]; File input = new File(strXMLFilename); // Prepare HTTP post PostMethod post = new PostMethod(strURL); // Request content will be retrieved directly // from the input stream // Per default, the request content needs to be buffered // in order to determine its length. // Request body buffering can be avoided when // content length is explicitly specified post.setRequestEntity(new InputStreamRequestEntity( new FileInputStream(input), input.length())); // Specify content type and encoding // If content encoding is not explicitly specified // ISO-8859-1 is assumed post.setRequestHeader( "Content-type", "text/xml; charset=ISO-8859-1"); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { int result = httpclient.executeMethod(post); // Display status code System.out.println("Response status code: " + result); // Display response System.out.println("Response body: "); System.out.println(post.getResponseBodyAsString()); } finally { // Release current connection to the connection pool // once you are done post.releaseConnection(); } } }

    Read the article

  • FaceBook Login Problem

    - by toman
    Hi All, I am for an application which extracts information from facebook search, hence i require to login facebook. i have registered my application in facebook developers site and have got api key and secret key. in my code i am getting an exception when i am trying to login. Here is my code for login to facebook: import com.facebook.api.FacebookRestClient; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpClientParams; public class FaceLogin { public FaceLogin(){ getUserID("username", "password"); } private static void getUserID(String email, String password) { String session = null; try { HttpClient http = new HttpClient(); http.setParams(new HttpClientParams()); //http.getHostConfiguration().setHost("http://www.facebook.com/"); http.setState(new HttpState()); String api_key = "****some key****"; String secret = "****some key****"; FacebookRestClient client = new FacebookRestClient(api_key, secret); client.setIsDesktop(true); String token = client.auth_createToken(); final String loginId = "http://www.facebook.com/login.php"; GetMethod get = new GetMethod(loginId + "?api_key=" + api_key + "&v=1.0&auth_token=" +token); System.out.println("Get="+get); http.executeMethod(get); PostMethod post = new PostMethod(loginId); post.addParameter(new NameValuePair("api_key", api_key)); post.addParameter(new NameValuePair("v", "1.0")); post.addParameter(new NameValuePair("auth_token", token)); post.addParameter(new NameValuePair("fbconnect","true")); post.addParameter(new NameValuePair("return_session","true")); post.addParameter(new NameValuePair("session_key_only","true")); post.addParameter(new NameValuePair("req_perms","read_stream,publish_stream")); post.addParameter(new NameValuePair("lsd","8HYdi")); post.addParameter(new NameValuePair("locale","en_US")); post.addParameter(new NameValuePair("persistent","1")); post.addParameter(new NameValuePair("email", email)); post.addParameter(new NameValuePair("pass", password)); System.out.println("Token ="+token); int postStatus = http.executeMethod(post); System.out.println("Response : " + postStatus); session = client.auth_getSession(token); // Here I am getting error System.out.println("Session string: " + session); long userid = client.users_getLoggedInUser(); System.out.println("User Id is : " + userid); } catch (Exception e) { e.printStackTrace(); } } public static void main(String k[]) { FaceLogin facebookLoginObj=new FaceLogin(); } } I am getting the following exception: org.apache.commons.httpclient.HttpMethodBase processResponseHeaders WARNING: Cookie rejected: "$Version=0; $Domain=deleted; $Path=/; $Domain=.facebook.com". Cookie name may not start with $ Response : 200 Jun 8, 2010 2:07:36 PM org.apache.commons.httpclient.HttpMethodBase processResponseHeaders WARNING: Cookie rejected: "$Version=0; $Path=deleted; $Path=/; $Domain=.facebook.com". Cookie name may not start with $ Facebook returns error code 100 com.facebook.api.FacebookException: Invalid parameter - v - 1.0 at com.facebook.api.FacebookRestClient.callMethod(FacebookRestClient.java:828) - auth_token - 004e90dc8818d5f0921d1065d24508d3 at com.facebook.api.FacebookRestClient.callMethod(FacebookRestClient.java:606) - method - facebook.auth.getSession - call_id - 1275986256796 - api_key - f7cb1e48c383ef599da9021fc4dec322 at com.facebook.api.FacebookRestClient.auth_getSession(FacebookRestClient.java:1891) at facebookcrawler.FacebookLogin.getUserID(FacebookLogin.java:81) at facebookcrawler.FacebookLogin.( - sig - 9344ec75b74a0a87bcae645046d45da8 FacebookLogin.java:24) at facebookcrawler.FaceLogin.main(FaceLogin.java:80) Here may be the problem is for creating session, i searched for all the solutions on net but could not helped me to get login. Please help me if you can suggest me some way to resolve this problem. i thanks to all your valuable suggestion.

    Read the article

  • How to set up dynamically Part in MultipartRequestEntity

    - by ee_vin
    Hello, I'm using commons-httpclient-3.1 inside my android application. And I would like to know if it possible to manipulate Part (org.apache.commons.httpclient.methods.multipart.Part) dynamically? Essentially adding new FilePart and new StringPart at runtime before sending the request. Every example I've found until now suppose that you know how many fields you are dealing with. Ex: File f = new File("/path/fileToUpload.txt"); PostMethod filePost = new PostMethod("http://host/some_path"); Part[] parts = { new StringPart("param_name", "value"), new FilePart(f.getName(), f) }; filePost.setRequestEntity( new MultipartRequestEntity(parts, filePost.getParams()) ); HttpClient client = new HttpClient(); int status = client.executeMethod(filePost); code from http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/methods/multipart/MultipartRequestEntity.html Android specific thread: http://groups.google.com/group/android-developers/browse_thread/thread/0f9e17bbaf50c5fc Thank you

    Read the article

  • Nginx virtual server only partially working with Java application

    - by MFB
    Final Cut Server is a Java application (made by Apple) which launches from a web page. I have Nginx in front of this web server (amongst others) and, whilst the web server can be browsed externally, the Java app fails to launch correctly and throws the errors below. Can anyone offer clues as to what additional config I many have to add to Nginx to get this working? My existing Nginx config: user xxxx; worker_processes 4; pid /var/run/nginx.pid; events { worker_connections 1024; # multi_accept on; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/conf/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; gzip_disable "msie6"; server { server_name _; return 444; } upstream fcs-site { server 10.10.5.20:8080; } server { listen 80; server_name example.com 10.10.5.90; access_log /var/log/nginx/fcs_access.log; error_log /var/log/nginx/fcs_error.log; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 60s; proxy_send_timeout 90s; proxy_read_timeout 90s; proxy_buffering off; proxy_temp_file_write_size 64k; proxy_pass http://fcs-site; proxy_redirect off; } } upstream myapp-site { server 127.0.0.1:6543; } server { listen 80; server_name otherexample.com www.otherexample.com; rewrite ^ https://$server_name$request_uri? permanent; } server { listen 443; ssl on; ssl_certificate /etc/ssl/otherapp.crt; ssl_certificate_key /etc/ssl/otherapp.key; server_name otherexample.com www.otherexample.com; access_log /var/log/nginx/otherapp_access.log; error_log /var/log/nginx/other_error.log; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 60s; proxy_send_timeout 90s; proxy_read_timeout 90s; proxy_buffering off; proxy_temp_file_write_size 64k; proxy_pass http://myapp-site; proxy_redirect off; } location /static { root /www; expires 30d; add_header Cache-Control public; access_log off; } } Java errors: com.sun.deploy.net.FailedDownloadException: Unable to load resource: http://example.com:8080/FinalCutServer/FinalCutServer_mac.jnlp at com.sun.deploy.net.DownloadEngine.actionDownload(Unknown Source) at com.sun.deploy.net.DownloadEngine._downloadCacheEntry(Unknown Source) at com.sun.deploy.cache.ResourceProviderImpl.getResourceCacheEntry(Unknown Source) at com.sun.deploy.cache.ResourceProviderImpl.getResourceCacheEntry(Unknown Source) at com.sun.deploy.cache.ResourceProviderImpl.getResource(Unknown Source) at com.sun.javaws.Launcher.updateFinalLaunchDesc(Unknown Source) at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source) at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source) at com.sun.javaws.Launcher.launch(Unknown Source) at com.sun.javaws.Main.launchApp(Unknown Source) at com.sun.javaws.Main.continueInSecureThread(Unknown Source) at com.sun.javaws.Main.access$000(Unknown Source) at com.sun.javaws.Main$1.run(Unknown Source) at java.lang.Thread.run(Thread.java:722) java.net.ConnectException: Operation timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at sun.net.NetworkClient.doConnect(NetworkClient.java:180) at sun.net.www.http.HttpClient.openServer(HttpClient.java:378) at sun.net.www.http.HttpClient.openServer(HttpClient.java:473) at sun.net.www.http.HttpClient.(HttpClient.java:203) at sun.net.www.http.HttpClient.New(HttpClient.java:290) at sun.net.www.http.HttpClient.New(HttpClient.java:306) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:995) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:931) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:849) at com.sun.deploy.net.BasicHttpRequest.doRequest(Unknown Source) at com.sun.deploy.net.BasicHttpRequest.doRequest(Unknown Source) at com.sun.deploy.net.BasicHttpRequest.doGetRequest(Unknown Source) at com.sun.deploy.net.DownloadEngine.actionDownload(Unknown Source) at com.sun.deploy.net.DownloadEngine._downloadCacheEntry(Unknown Source) at com.sun.deploy.cache.ResourceProviderImpl.getResourceCacheEntry(Unknown Source) at com.sun.deploy.cache.ResourceProviderImpl.getResourceCacheEntry(Unknown Source) at com.sun.deploy.cache.ResourceProviderImpl.getResource(Unknown Source) at com.sun.javaws.Launcher.updateFinalLaunchDesc(Unknown Source) at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source) at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source) at com.sun.javaws.Launcher.launch(Unknown Source) at com.sun.javaws.Main.launchApp(Unknown Source) at com.sun.javaws.Main.continueInSecureThread(Unknown Source) at com.sun.javaws.Main.access$000(Unknown Source) at com.sun.javaws.Main$1.run(Unknown Source) at java.lang.Thread.run(Thread.java:722)

    Read the article

  • Java getInputStreat SocketTimeoutException instead of NoRouteToHostException

    - by Jon
    I have an odd issue happening when trying to open multiple Input Streams (in separate threads) on Linux (RHEL). The behaviour works as expected on windows. I am kicking off 3 threads to open https connections to 3 different servers. All three are invalid IP addresses (in this test case), so I expect an NoRouteToHostException for each of them. The first two return these as expected, and quite quickly. (see stack trace below) However the third (and 4th when I tested it that way) do NOT give a no route exception. They wait for ages, and then give a SocketTimeoutException (see other stack trace below). This takes ages to come back, and does not accurately express the connection issue. The offending line of code is: reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); Has anyone seen something like this before? Are there multi-threading issues with sockets on REHL or some limit somewhere to how many can connect at once...or...something? Expected stack trace, as received for first two: java.net.NoRouteToHostException: No route to host at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:529) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:559) at sun.net.NetworkClient.doConnect(NetworkClient.java:158) at sun.net.www.http.HttpClient.openServer(HttpClient.java:394) at sun.net.www.http.HttpClient.openServer(HttpClient.java:529) at sun.net.www.protocol.https.HttpsClient.(HttpsClient.java:272) at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:329) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:916) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1177) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234) Unexpected stack trace, as received on 3rd: java.net.SocketTimeoutException: connect timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:529) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:559) at sun.net.NetworkClient.doConnect(NetworkClient.java:158) at sun.net.www.http.HttpClient.openServer(HttpClient.java:394) at sun.net.www.http.HttpClient.openServer(HttpClient.java:529) at sun.net.www.protocol.https.HttpsClient.(HttpsClient.java:272) at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:329) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:916) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1177) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)

    Read the article

  • How can I get jcifs to play nicely with apache axis

    - by Ben Hammond
    I need to connect Apache Axis 1.4 to a Webservice that uses NTLM authentication to restrict access to its operations. I'm expecting to use Samba Jcifs to handle the NTLM handshake. I found http://hc.apache.org/httpcomponents-client/ntlm.html which gives me fantastic directions for how to wire up HttpClient 4.0 with jcifs. Trouble is, Axis wants to use Http Client 3.0 and the two apis look very different. There are 2 possibilities that I can see Write an object for Axis that lets it plug into HttpClient 4. Figure out how to wire HttpClient 3.0 up with Samba Jcifs. Number 1. looks non-trivial, but possible Number 2. I cannot find any encouraging messages on the web describing how to do this. My question is: has anyone successfully connected samba jcifs with HttpClient 3.0 ? Has anyone already created an Axis HttpSender object that works with HttpClient 4 ? Is there some better alternative that I have not considered?

    Read the article

  • apache commons http client efficiency

    - by wo_shi_ni_ba_ba
    I use apache commons http client to send data via post every second, is there a way to make the following code more efficient? I know http is stateless, but is there anything I can do to improve since the base url is always the same in this case(only the parameter value change. private void sendData(String s){ try { HttpClient client = getHttpClient(); HttpPost method = new HttpPost("http://192.168.1.100:8080/myapp"); System.err.println("send to server "+s); List formparams = new ArrayList(); formparams.add(new BasicNameValuePair("packet", s)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); method.setEntity(entity); HttpResponse resp=client.execute(method); String res = EntityUtils.toString(resp.getEntity()); System.out.println(res); } catch (Exception e) { e.printStackTrace(); } } private HttpClient getHttpClient() { if(httpClient==null){ httpClient = new DefaultHttpClient(); } return httpClient; }

    Read the article

  • How OpenStack Swift handles concurrent restful API request?

    - by Chen Xie
    I installed a swift service and was trying to know the capability of handling concurrent request. So I created massive amount of threads in Java, and sent it via the RestFUL API Not surprisingly, when the number of requests climb up, the program started to throw out exceptions. Caused by: java.net.ConnectException: Connection timed out: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at sun.net.NetworkClient.doConnect(NetworkClient.java:180) at sun.net.www.http.HttpClient.openServer(HttpClient.java:378) at sun.net.www.http.HttpClient.openServer(HttpClient.java:473) at sun.net.www.http.HttpClient.(HttpClient.java:203) But can anyone tell me how that time outhappened? I am curious of how SWIFT handles those requests. Is that by queuing the requests and because there are too many requests in the queue and wait for too long time and it's just get kicked out from the queue? If this holds, does it mean that it's an asynchronized mechanism to handle requests? Thanks.

    Read the article

  • Strange Jmeter connection refuse on Tomcat

    - by Tommy
    I tried difference setting in Jmeter and Tomcat. If the Threads number in JMeter is 1~200, Then tomcat is okay. If It is 300, Then after serving few requests, tomcat starts to output errors. Here is the error show in JMeter java.net.ConnectException: Connection refused: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(Unknown Source) at java.net.PlainSocketImpl.connectToAddress(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at sun.net.NetworkClient.doConnect(Unknown Source) at sun.net.www.http.HttpClient.openServer(Unknown Source) at sun.net.www.http.HttpClient.openServer(Unknown Source) at sun.net.www.http.HttpClient.<init>(Unknown Source) at sun.net.www.http.HttpClient.New(Unknown Source) at sun.net.www.http.HttpClient.New(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source) at org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.sample(HTTPJavaImpl.java:483) at org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy.sample(HTTPSamplerProxy.java:62) at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1018) at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1004) at org.apache.jmeter.threads.JMeterThread.process_sampler(JMeterThread.java:411) at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:297) at java.lang.Thread.run(Unknown Source) My tomcat server.xml in eclipse <!--The connectors can use a shared executor, you can define one or more named thread pools--> <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="2000" minSpareThreads="250" acceptCount="2000"/> <Connector executor="tomcatThreadPool" URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" /> Any idea why this is happening ? How do i check the server.xml is correctly used? It is a JSF2 application if it helps. Thanks in advance.

    Read the article

  • C# 5.0 Async/Await Demo Code

    - by Paulo Morgado
    I’ve published the sample code I use to demonstrate the use of async/await in C# 5.0. You can find it here. Projects PauloMorgado.AyncDemo.WebServer This project is a simple web server implemented as a console application using Microsoft ASP.NET Web API self hosting and serves an image (with a delay) that is accessed by the other projects. This project has a dependency on Json.NET due to the fact the the Microsoft ASP.NET Web API hosting has a dependency on Json.NET. The application must be run on a command prompt with administrative privileges or a urlacl must be added to allow the use of the following command: netsh http add urlacl url=http://+:9090/ user=machine\username To remove the urlacl, just use the following command: netsh http delete urlacl url=http://+:9090/ PauloMorgado.AsyncDemo.WindowsForms This Windows Forms project contains three regions that must be uncommented one at a time: Sync with WebClient This code retrieves the image through a synchronous call using the WebClient class. Async with WebClient This code retrieves the image through an asynchronous call using the WebClient class. Async with HttpClient with cancelation This code retrieves the image through an asynchronous call with cancelation using the HttpClient class. PauloMorgado.AsyncDemo.Wpf This WPF project contains three regions that must be uncommented one at a time: Sync with WebClient This code retrieves the image through a synchronous call using the WebClient class. Async with WebClient This code retrieves the image through an asynchronous call using the WebClient class. Async with HttpClient with cancelation This code retrieves the image through an asynchronous call with cancelation using the HttpClient class.

    Read the article

  • Consuming the Amazon S3 service from a Win8 Metro Application

    - by cibrax
    As many of the existing Http APIs for Cloud Services, AWS also provides a set of different platform SDKs for hiding many of complexities present in the APIs. While there is a platform SDK for .NET, which is open source and available in C#, that SDK does not work in Win8 Metro Applications for the changes introduced in WinRT. WinRT offers a complete different set of APIs for doing I/O operations such as doing http calls or using cryptography for signing or encrypting data, two aspects that are absolutely necessary for consuming AWS. All the I/O APIs available as part of WinRT are asynchronous, and uses the TPL model for .NET applications (HTML and JavaScript Metro applications use a model based in promises, which is similar concept).  In the case of S3, the http Authorization header is used for two purposes, authenticating clients and make sure the messages were not altered while they were in transit. For doing that, it uses a signature or hash of the message content and some of the headers using a symmetric key (That's just one of the available mechanisms). Windows Azure for example also uses the same mechanism in many of its APIs. There are three challenges that any developer working for first time in Metro will have to face to consume S3, the new WinRT APIs, the asynchronous nature of them and the complexity introduced for generating the Authorization header. Having said that, I decided to write this post with some of the gotchas I found myself trying to consume this Amazon service. 1. Generating the signature for the Authorization header All the cryptography APIs in WinRT are available under Windows.Security.Cryptography namespace. Many of operations available in these APIs uses the concept of buffers (IBuffer) for representing a chunk of binary data. As you will see in the example below, these buffers are mainly generated with the use of static methods in a WinRT class CryptographicBuffer available as part of the namespace previously mentioned. private string DeriveAuthToken(string resource, string httpMethod, string timestamp) { var stringToSign = string.Format("{0}\n" + "\n" + "\n" + "\n" + "x-amz-date:{1}\n" + "/{2}/", httpMethod, timestamp, resource); var algorithm = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1"); var keyMaterial = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(this.secret)); var hmacKey = algorithm.CreateKey(keyMaterial); var signature = CryptographicEngine.Sign( hmacKey, CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(stringToSign)) ); return CryptographicBuffer.EncodeToBase64String(signature); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } The algorithm that determines the information or content you need to use for generating the signature is very well described as part of the AWS documentation. In this case, this method is generating a signature required for creating a new bucket. A HmacSha1 hash is computed using a secret or symetric key provided by AWS in the management console. 2. Sending an Http Request to the S3 service WinRT also ships with the System.Net.Http.HttpClient that was first introduced some months ago with ASP.NET Web API. This client provides a rich interface on top the traditional WebHttpRequest class, and also solves some of limitations found in this last one. There are a few things that don't work with a raw WebHttpRequest such as setting the Host header, which is something absolutely required for consuming S3. Also, HttpClient is more friendly for doing unit tests, as it receives a HttpMessageHandler as part of the constructor that can fake to emulate a real http call. This is how the code for consuming the service with HttpClient looks like, public async Task<S3Response> CreateBucket(string name, string region = null, params string[] acl) { var timestamp = string.Format("{0:r}", DateTime.UtcNow); var auth = DeriveAuthToken(name, "PUT", timestamp); var request = new HttpRequestMessage(HttpMethod.Put, "http://s3.amazonaws.com/"); request.Headers.Host = string.Format("{0}.s3.amazonaws.com", name); request.Headers.TryAddWithoutValidation("Authorization", "AWS " + this.key + ":" + auth); request.Headers.Add("x-amz-date", timestamp); var client = new HttpClient(); var response = await client.SendAsync(request); return new S3Response { Succeed = response.StatusCode == HttpStatusCode.OK, Message = (response.Content != null) ? await response.Content.ReadAsStringAsync() : null }; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } You will notice a few additional things in this code. By default, HttpClient validates the values for some well-know headers, and Authorization is one of them. It won't allow you to set a value with ":" on it, which is something that S3 expects. However, that's not a problem at all, as you can skip the validation by using the TryAddWithoutValidation method. Also, the code is heavily relying on the new async and await keywords to transform all the asynchronous calls into synchronous ones. In case you would want to unit test this code and faking the call to the real S3 service, you should have to modify it to inject a custom HttpMessageHandler into the HttpClient. The following implementation illustrates this concept, In case you would want to unit test this code and faking the call to the real S3 service, you should have to modify it to inject a custom HttpMessageHandler into the HttpClient. The following implementation illustrates this concept, public class FakeHttpMessageHandler : HttpMessageHandler { HttpResponseMessage response; public FakeHttpMessageHandler(HttpResponseMessage response) { this.response = response; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetResult(response); return tcs.Task; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } You can use this handler for injecting any response while you are unit testing the code.

    Read the article

  • Consuming the Amazon S3 service from a Win8 Metro Application

    - by cibrax
    As many of the existing Http APIs for Cloud Services, AWS also provides a set of different platform SDKs for hiding many of complexities present in the APIs. While there is a platform SDK for .NET, which is open source and available in C#, that SDK does not work in Win8 Metro Applications for the changes introduced in WinRT. WinRT offers a complete different set of APIs for doing I/O operations such as doing http calls or using cryptography for signing or encrypting data, two aspects that are absolutely necessary for consuming AWS. All the I/O APIs available as part of WinRT are asynchronous, and uses the TPL model for .NET applications (HTML and JavaScript Metro applications use a model based in promises, which is similar concept).  In the case of S3, the http Authorization header is used for two purposes, authenticating clients and make sure the messages were not altered while they were in transit. For doing that, it uses a signature or hash of the message content and some of the headers using a symmetric key (That's just one of the available mechanisms). Windows Azure for example also uses the same mechanism in many of its APIs. There are three challenges that any developer working for first time in Metro will have to face to consume S3, the new WinRT APIs, the asynchronous nature of them and the complexity introduced for generating the Authorization header. Having said that, I decided to write this post with some of the gotchas I found myself trying to consume this Amazon service. 1. Generating the signature for the Authorization header All the cryptography APIs in WinRT are available under Windows.Security.Cryptography namespace. Many of operations available in these APIs uses the concept of buffers (IBuffer) for representing a chunk of binary data. As you will see in the example below, these buffers are mainly generated with the use of static methods in a WinRT class CryptographicBuffer available as part of the namespace previously mentioned. private string DeriveAuthToken(string resource, string httpMethod, string timestamp) { var stringToSign = string.Format("{0}\n" + "\n" + "\n" + "\n" + "x-amz-date:{1}\n" + "/{2}/", httpMethod, timestamp, resource); var algorithm = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1"); var keyMaterial = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(this.secret)); var hmacKey = algorithm.CreateKey(keyMaterial); var signature = CryptographicEngine.Sign( hmacKey, CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(stringToSign)) ); return CryptographicBuffer.EncodeToBase64String(signature); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } The algorithm that determines the information or content you need to use for generating the signature is very well described as part of the AWS documentation. In this case, this method is generating a signature required for creating a new bucket. A HmacSha1 hash is computed using a secret or symetric key provided by AWS in the management console. 2. Sending an Http Request to the S3 service WinRT also ships with the System.Net.Http.HttpClient that was first introduced some months ago with ASP.NET Web API. This client provides a rich interface on top the traditional WebHttpRequest class, and also solves some of limitations found in this last one. There are a few things that don't work with a raw WebHttpRequest such as setting the Host header, which is something absolutely required for consuming S3. Also, HttpClient is more friendly for doing unit tests, as it receives a HttpMessageHandler as part of the constructor that can fake to emulate a real http call. This is how the code for consuming the service with HttpClient looks like, public async Task<S3Response> CreateBucket(string name, string region = null, params string[] acl) { var timestamp = string.Format("{0:r}", DateTime.UtcNow); var auth = DeriveAuthToken(name, "PUT", timestamp); var request = new HttpRequestMessage(HttpMethod.Put, "http://s3.amazonaws.com/"); request.Headers.Host = string.Format("{0}.s3.amazonaws.com", name); request.Headers.TryAddWithoutValidation("Authorization", "AWS " + this.key + ":" + auth); request.Headers.Add("x-amz-date", timestamp); var client = new HttpClient(); var response = await client.SendAsync(request); return new S3Response { Succeed = response.StatusCode == HttpStatusCode.OK, Message = (response.Content != null) ? await response.Content.ReadAsStringAsync() : null }; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } You will notice a few additional things in this code. By default, HttpClient validates the values for some well-know headers, and Authorization is one of them. It won't allow you to set a value with ":" on it, which is something that S3 expects. However, that's not a problem at all, as you can skip the validation by using the TryAddWithoutValidation method. Also, the code is heavily relying on the new async and await keywords to transform all the asynchronous calls into synchronous ones. In case you would want to unit test this code and faking the call to the real S3 service, you should have to modify it to inject a custom HttpMessageHandler into the HttpClient. The following implementation illustrates this concept, In case you would want to unit test this code and faking the call to the real S3 service, you should have to modify it to inject a custom HttpMessageHandler into the HttpClient. The following implementation illustrates this concept, public class FakeHttpMessageHandler : HttpMessageHandler { HttpResponseMessage response; public FakeHttpMessageHandler(HttpResponseMessage response) { this.response = response; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetResult(response); return tcs.Task; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } You can use this handler for injecting any response while you are unit testing the code.

    Read the article

  • C# 5 - asynch method callback with Task.ContinueWIth? [migrated]

    - by user1142433
    I have a method that pulls some HTML via the HttpClient like so: public static HttpClient web = new HttpClient(); public static async Task<string> GetHTMLDataAsync(string url) { string responseBodyAsText = ""; try { HttpResponseMessage response = await web.GetAsync(url); response.EnsureSuccessStatusCode(); responseBodyAsText = await response.Content.ReadAsStringAsync(); } catch (Exception e) { // Error handling } return responseBodyAsText; } I have another method that looks like so: private void HtmlReadComplete(string data) { // do something with the data } I would like to be able to call GetHTMLDataAsync and then have it call HtmlReadComplete on the UI thread when the html has been read. I naively thought this could somehow be done with something that looks like GetHTMLDataAsync(url).ContinueWith(HtmlReadComplete); But, I can't get the syntax correct, nor am I even sure that's the appropriate way to handle it. Thanks in advance!

    Read the article

  • Download a file with DefaultHTTPClient and preemptive authentication

    - by Nils
    After I had a lot of problems with preemptive authentication , I got it finally working. Now the next problem. I want to get a file with it, but I don't know how. I thought the file data might be in the variable response, but it isn't. Any ideas how this might work? I'm trying it since days without success :( - Basically I'm trying to download an jpeg file, which is on a server protected by prem. auth. // BASIC AUTH /* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ //http://svn.apache.org/repos/asf/httpcomponents/httpclient/branches/4.0.x/httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveBasicAuthentication.java httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials( new AuthScope(host, port), new UsernamePasswordCredentials(username, password)); // Generate BASIC scheme object and stick it to the local // execution context BasicHttpContext localcontext = new BasicHttpContext(); BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); //first request interceptor httpclient.addRequestInterceptor(new PreemptiveAuth(), 0); HttpHost targetHost = new HttpHost(host, port, "http"); //HttpGet httpget = new HttpGet("/"); HttpGet httpget = new HttpGet(http.url); System.out.println("executing request" + httpget.getRequestLine()); /// !!! HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println("+"+response.getStatusLine()+"+"); ...

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >