Search Results

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

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

  • HTTP Post requests using HttpClient take 2 seconds, why?

    - by pableu
    Update: You might better hold off this for a bit, I just noticed I could be my fault after all. Working on this all afternoon, and then I find a flaw ten minutes after posting here, ts. Hi, I'am currently coding an android app that submits stuff in the background using HTTP Post and AsyncTask. I use the org.apache.http.client Package for this. I based my code on this example. Basically, my code looks like this: public void postData() { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.168.1.137:8880/form"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("id", "12345")); nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); } catch (ClientProtocolException e) { Log.e(TAG,e.toString()); } catch (IOException e) { Log.e(TAG,e.toString()); } } The problem is that the httpclient.execute(..) line takes around 1.5 to 3 seconds, and I do not understand why. Just requesting a page with HTTP Get takes around 80 ms or so, so the problem doesn't seem to be the network latency itself. The problem doesn't seem to be on the server side either, I have also tried POSTing data to http://www.disney.com/ with similarly slow results. And Firebug shows 1 ms response time when POSTing data to my server locally. This happens on the Emulator and with my Nexus One (both with Android 2.2). If you want to look at the complete code, I've put it on GitHub. It's just a dummy program to do HTTP Post in the background using AsyncTask on the push of a button. It's my first Android app, and my first java code for a long time. And incidentially, also my first question on Stackoverflow ;-) Any ideas why httpclient.execute(httppost) takes so long?

    Read the article

  • Is this a good implementation of DefaultHttpClient and ThreadSafeClientConnManager in Android?

    - by johnrock
    In my Android app I am sharing one httpclient for all activities/threads. All requests are made by callling getHttpClient().execute(httpget) or getHttpClient().execute(httppost). Is this implementation complete/correct and safe for multiple threads? Is there anything else missing i.e. Do I have to worry about releasing connections at all? private static HttpClient httpclient ; public static HttpClient getHttpClient() { if(httpclient == null){ return getHttpClientNew(); } else{ return httpclient; } } public static synchronized HttpClient getHttpClientNew() { HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 100); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF_8"); HttpProtocolParams.setUseExpectContinue(params, false); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); httpclient = new DefaultHttpClient(cm, params); return httpclient; } This is an example of how the httpclient is used: private void update() { HttpGet httpget = new HttpGet(URL); httpget.setHeader(USER_AGENT, userAgent); httpget.setHeader(CONTENT_TYPE, MGUtils.APP_XML); HttpResponse response; try { response = getHttpClient().execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { // parse stuff } } catch (Exception e) { } }

    Read the article

  • Apache HttpClient 4.0. Weird behavior.

    - by Mikhail T
    Hello. I'm using Apache HttpClient 4.0 for my web crawler. The behavior i found strange is: i'm trying to get page via HTTP GET method and getting response about 404 HTTP error. But if i try to get that page using browser it's done successfully. Details: 1. I upload multipart form to server this way: HttpPost httpPost = new HttpPost("http://[host here]/in.php"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("method", new StringBody("post")); entity.addPart("key", new StringBody("223fwe0923fjf23")); FileBody fileBody = new FileBody(new File("photo.jpg"), "image/jpeg"); entity.addPart("file", fileBody); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); HttpEntity result = response.getEntity(); String responseString = ""; if (result != null) { InputStream inputStream = result.getContent(); byte[] buffer = new byte[1024]; while(inputStream.read(buffer) > 0) responseString += new String(buffer); result.consumeContent(); } Uppload succefully ends. I'm getting some results from web server: HttpGet httpGet = new HttpGet("http://[host here]/res.php?key="+myKey+"&action=get&id="+id); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); I'm getting ClientProtocolException while execute method run. I was debugging this situation with log4j. Server answers "404 Not Found". But my browser loads me that page with no problem. Can anybody help me? Thank you.

    Read the article

  • NoClassDefFoundError: HttpClient 4 (APACHE)

    - by Pujan Srivastava
    Hello All, I am using HC APACHE. I have added both httpcore-4.0.1.jar and httpclient-4.0.1.jar in the classpath of netbeans. I am getting error: java.lang.NoClassDefFoundError: org/apache/http/impl/client/DefaultHttpClient My Code is as follows. Please help. import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; public class HttpClientManager { public HttpClient httpclient; public HttpClientManager() { this.init(); } public void init() { try { httpclient = new DefaultHttpClient(); } catch (Exception e) { e.printStackTrace(); } } public void getCourseList() { String url = "http://exnet.in.th/api.php?username=demoinst&ha=2b62560&type=instructor"; HttpGet httpget = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { String responseBody = httpclient.execute(httpget, responseHandler); System.out.println(responseBody); } catch (Exception e) { } } }

    Read the article

  • Why do I get empty request from the Jakarta Commons HttpClient?

    - by polyurethan
    I have a problem with the Jakarta Commons HttpClient. Before my self-written HttpServer gets the real request there is one request which is completely empty. That's the first problem. The second problem is, sometimes the request data ends after the third or fourth line of the http request: POST / HTTP/1.1 User-Agent: Jakarta Commons-HttpClient/3.1 Host: 127.0.0.1:4232 For debugging I am using the Axis TCPMonitor. There every things is fine but the empty request. How I process the stream: StringBuffer requestBuffer = new StringBuffer(); InputStreamReader is = new InputStreamReader(socket.getInputStream(), "UTF-8"); int byteIn = -1; do { byteIn = is.read(); if (byteIn > 0) { requestBuffer.append((char) byteIn); } } while (byteIn != -1 && is.ready()); String requestData = requestBuffer.toString(); How I send the request: client.getParams().setSoTimeout(30000); method = new PostMethod(url.getPath()); method.getParams().setContentCharset("utf-8"); method.setRequestHeader("Content-Type", "application/xml; charset=utf-8"); method.addRequestHeader("Connection", "close"); method.setFollowRedirects(false); byte[] requestXml = getRequestXml(); method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(requestXml))); client.executeMethod(method); int statusCode = method.getStatusCode(); Have anyone of you an idea how to solve these problems? Alex

    Read the article

  • How to properly encode "[" and "]" in queries using Apache HttpClient?

    - by Jason Nichols
    I've got a GET method that looks like the following: GetMethod method = new GetMethod("http://host/path/?key=[\"item\",\"item\"]"); Such a path works just fine when typed directly into a browser, but the above line when run causes an IllegalArgumentException : Invalid URI. I've looked at using the URIUtils class, but without success. Is there a way to automatically encode this (or to add a query string onto the URL without causing HttpClient to barf?).

    Read the article

  • SSLException: HelloRequest followed by an unexpected handshake message

    - by mseebach
    I'm trying to connect to a webservice over SSL using Apache Commons HttpClient 3.1, using this: String url = "https://archprod.service.eogs.dk/cvronline/esb/LegalUnitGetSSLServicePort"; HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); StringRequestEntity entity = new StringRequestEntity(requestXml, "application/soap+xml", "utf-8"); post.setRequestEntity(entity); client.executeMethod(post); String response = post.getResponseBodyAsString(); And I get this exception: javax.net.ssl.SSLException: HelloRequest followed by an unexpected handshake message at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:190) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1623) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:198) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:188) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverHelloRequest(ClientHandshaker.java:286) at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:114) at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:525) at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:465) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:884) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:746) at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75) at java.io.BufferedInputStream.fill(BufferedInputStream.java:218) at java.io.BufferedInputStream.read(BufferedInputStream.java:237) at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:78) at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:106) at org.apache.commons.httpclient.HttpConnection.readLine(HttpConnection.java:1116) at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1973) at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1735) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1098) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) A request to the same URL on the same machine, using curl, works fine - and if I change the URL to e.g. https://www.verisign.com, it works fine in Java, too. So it appears to be the specific combination of Java and that host, not a general problem. Ubuntu 10.04 beta, Sun JDK 1.6.0_19 (same problem in Ubuntu's bundled OpenJDK 6b18~pre4). Any ideas what's going wrong? Thanks!

    Read the article

  • KeyStore, HttpClient, and HTTPS: Can someone explain this code to me?

    - by stormin986
    I'm trying to understand what's going on in this code. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("my.keystore")); try { trustStore.load(instream, "nopassword".toCharArray()); } finally { instream.close(); } SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); Scheme sch = new Scheme("https", socketFactory, 443); httpclient.getConnectionManager().getSchemeRegistry().register(sch); My Questions: trustStore.load(instream, "nopassword".toCharArray()); is doing what exactly? From reading the documentation load() will load KeyStore data from an input stream (which is just an empty file we just created), using some arbitrary "nopassword". Why not just load it with null as the InputStream parameter and an empty string as the password field? And then what is happening when this empty KeyStore is being passed to the SSLSocketFactory constructor? What's the result of such an operation? Or -- is this simply an example where in a real application you would have to actually put a reference to an existing keystore file / password?

    Read the article

  • Just need someone familiar with HTTPClient to check over a piece of code

    - by jax
    here are two little helper methods I have made for downloading files. I have had to mix and match different tutorials of the web to get what I have here. Now is there anything that I have done blatantly wrong here? public static InputStream simplePostRequest(URL url, List<NameValuePair> postData) throws ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost postMethod=new HttpPost(url.toExternalForm()); postMethod.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8)); HttpResponse response = httpclient.execute(postMethod); HttpEntity entity = response.getEntity(); return entity.getContent(); } public static InputStream simpleGetRequest(URL url, List<NameValuePair> queryString) throws ClientProtocolException, IOException { Uri.Builder uri = new Uri.Builder(); uri.path(url.getPath()); for(NameValuePair nvp: queryString) { uri.appendQueryParameter(nvp.getName(), nvp.getValue()); } DefaultHttpClient httpClient = new DefaultHttpClient(); HttpHost host = new HttpHost(url.getHost()); HttpResponse response = httpClient.execute(host, new HttpGet(uri.build().toString())); HttpEntity entity = response.getEntity(); return entity.getContent(); }

    Read the article

  • Why is HttpClient's GetStringAsync is unbelivable slow?

    - by Jason94
    I have a Windows Phone 8 project where I've taken to use the PCL (Portable Class Library) project too since I'm going to build a Win8 app to. However, while calling my api (in Azure) my HttpClient's GetStringAsync is so slow. I threw in a couple of debugs with datetime and GetStringAsync took like 14 seconds! And sometimes it takes longer. What I'm doing is retrieving simple JSON from my Azure API site. My Android client has no problem with getting that same data in a split second... so is there something I'm missing? The setup is pretty straight forward: HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("X-Token", "something"); string responseJSON = await client.GetStringAsync("url"); I've places the debug times right before and after the await there, in between it is 14 seconds! Does someone know why?

    Read the article

  • Using HTTP Pipelining with Jetty HTTPClient

    - by jrogi
    I'm trying to figure out how to use HTTPClient (org.eclipse.jetty.client.HttpClient) so it will pipeline HTTP Request. I've tried to create some HttpExchange instances and applying the send() method for each, in an asynchronous mode, but each HTTP request has waited for it response before the next request was sent. Can you please supply a code snippet for this case?

    Read the article

  • Android: HTTPClient

    - 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

  • httpClient proxy support in apache commons 3.1

    - by user1173339
    I am using apache commons 3.1 to implement httpClient with proxy support. I am trying to connect to a remote host through proxy. The proxy server is configured without any authentication, however the the remote host is configured with authentication. When I am passing the proxy parameters through properties file, it gives warning while execution: WARN - Required proxy credentials not available for BASIC @xx.xx.xx.xx WARN - Preemptive authentication requested but no default proxy credentials availble But the execution goes ahead. On the other hand when I am passing the proxy parameters through the JVM arguments then the again the same warning is given and the execution is stopped. Is there any specific reason for this behavior? Is there any difference in passing the proxy parameters through properties file and through JVM arg? Here is the code: if(System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) { httpClient.getHostConfiguration().setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort"))); } else if(AMXAdminTask.props.getProperty("http.proxyHost") != null && AMXAdminTask.props.getProperty("http.proxyPort") != null) { httpClient.getHostConfiguration().setProxy(Propfile.props.getProperty("http.proxyHost"), Integer.parseInt(Propfile.props.getProperty("http.proxyPort"))); }

    Read the article

  • Coding With Windows Azure IaaS

    - by Hisham El-bereky
    This post will focus on some advanced programming topics concerned with IaaS (Infrastructure as a Service) which provided as windows azure virtual machine (with its related resources like virtual disk and virtual network), you know that windows azure started as PaaS cloud platform but regarding to some business cases which need to have full control over their virtual machine, so windows azure directed toward providing IaaS. Sometimes you will need to manage your cloud IaaS through code may be for these reasons: Working on hyper-cloud system by providing bursting connector to windows azure virtual machines Providing multi-tenant system which consume windows azure virtual machine Automated process on your on-premises or cloud service which need to utilize some virtual resources We are going to implement the following basic operation using C# code: List images Create virtual machine List virtual machines Restart virtual machine Delete virtual machine Before going to implement the above operations we need to prepare client side and windows azure subscription to communicate correctly by providing management certificate (x.509 v3 certificates) which permit client access to resources in your Windows Azure subscription, whilst requests made using the Windows Azure Service Management REST API require authentication against a certificate that you provide to Windows Azure More info about setting management certificate located here. And to install .cer on other client machine you will need the .pfx file, or if not exist by exporting .cer as .pfx Note: You will need to install .net 4.5 on your machine to try the code So let start This post built on the post sent by Michael Washam "Advanced Windows Azure IaaS – Demo Code", so I'm here to declare some points and to add new operation which is not exist in Michael's demo The basic C# class object used here as client to azure REST API for IaaS service is HttpClient (Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI) this object must be initialized with the required data like certificate, headers and content if required. Also I'd like to refer here that the code is based on using Asynchronous programming with calls to azure which enhance the performance and gives us the ability to work with complex calls which depends on more than one sub-call to achieve some operation The following code explain how to get certificate and initializing HttpClient object with required data like headers and content HttpClient GetHttpClient() { X509Store certificateStore = null; X509Certificate2 certificate = null; try { certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); certificateStore.Open(OpenFlags.ReadOnly); string thumbprint = ConfigurationManager.AppSettings["CertThumbprint"]; var certificates = certificateStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if (certificates.Count > 0) { certificate = certificates[0]; } } finally { if (certificateStore != null) certificateStore.Close(); }   WebRequestHandler handler = new WebRequestHandler(); if (certificate!= null) { handler.ClientCertificates.Add(certificate); HttpClient httpClient = new HttpClient(handler); //And to set required headers lik x-ms-version httpClient.DefaultRequestHeaders.Add("x-ms-version", "2012-03-01"); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); return httpClient; } return null; }  Let us keep the object httpClient as reference object used to call windows azure REST API IaaS service. For each request operation we need to define: Request URI HTTP Method Headers Content body (1) List images The List OS Images operation retrieves a list of the OS images from the image repository Request URI https://management.core.windows.net/<subscription-id>/services/images] Replace <subscription-id> with your windows Id HTTP Method GET (HTTP 1.1) Headers x-ms-version: 2012-03-01 Body None.  C# Code List<String> imageList = new List<String>(); //replace _subscriptionid with your WA subscription String uri = String.Format("https://management.core.windows.net/{0}/services/images", _subscriptionid);  HttpClient http = GetHttpClient(); Stream responseStream = await http.GetStreamAsync(uri);  if (responseStream != null) {      XDocument xml = XDocument.Load(responseStream);      var images = xml.Root.Descendants(ns + "OSImage").Where(i => i.Element(ns + "OS").Value == "Windows");      foreach (var image in images)      {      string img = image.Element(ns + "Name").Value;      imageList.Add(img);      } } More information about the REST call (Request/Response) located here on this link http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx (2) Create Virtual Machine Creating virtual machine required service and deployment to be created first, so creating VM should be done through three steps incase hosted service and deployment is not created yet Create hosted service, a container for service deployments in Windows Azure. A subscription may have zero or more hosted services Create deployment, a service that is running on Windows Azure. A deployment may be running in either the staging or production deployment environment. It may be managed either by referencing its deployment ID, or by referencing the deployment environment in which it's running. Create virtual machine, the previous two steps info required here in this step I suggest here to use the same name for service, deployment and service to make it easy to manage virtual machines Note: A name for the hosted service that is unique within Windows Azure. This name is the DNS prefix name and can be used to access the hosted service. For example: http://ServiceName.cloudapp.net// 2.1 Create service Request URI https://management.core.windows.net/<subscription-id>/services/hostedservices HTTP Method POST (HTTP 1.1) Header x-ms-version: 2012-03-01 Content-Type: application/xml Body More details about request body (and other information) are located here http://msdn.microsoft.com/en-us/library/windowsazure/gg441304.aspx C# code The following method show how to create hosted service async public Task<String> NewAzureCloudService(String ServiceName, String Location, String AffinityGroup, String subscriptionid) { String requestID = String.Empty;   String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices", subscriptionid); HttpClient http = GetHttpClient();   System.Text.ASCIIEncoding ae = new System.Text.ASCIIEncoding(); byte[] svcNameBytes = ae.GetBytes(ServiceName);   String locationEl = String.Empty; String locationVal = String.Empty;   if (String.IsNullOrEmpty(Location) == false) { locationEl = "Location"; locationVal = Location; } else { locationEl = "AffinityGroup"; locationVal = AffinityGroup; }   XElement srcTree = new XElement("CreateHostedService", new XAttribute(XNamespace.Xmlns + "i", ns1), new XElement("ServiceName", ServiceName), new XElement("Label", Convert.ToBase64String(svcNameBytes)), new XElement(locationEl, locationVal) ); ApplyNamespace(srcTree, ns);   XDocument CSXML = new XDocument(srcTree); HttpContent content = new StringContent(CSXML.ToString()); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml");   HttpResponseMessage responseMsg = await http.PostAsync(uri, content); if (responseMsg != null) { requestID = responseMsg.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } return requestID; } 2.2 Create Deployment Request URI https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deploymentslots/<deployment-slot-name> <deployment-slot-name> with staging or production, depending on where you wish to deploy your service package <service-name> provided as input from the previous step HTTP Method POST (HTTP 1.1) Header x-ms-version: 2012-03-01 Content-Type: application/xml Body More details about request body (and other information) are located here http://msdn.microsoft.com/en-us/library/windowsazure/ee460813.aspx C# code The following method show how to create hosted service deployment async public Task<String> NewAzureVMDeployment(String ServiceName, String VMName, String VNETName, XDocument VMXML, XDocument DNSXML) { String requestID = String.Empty;     String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments", _subscriptionid, ServiceName); HttpClient http = GetHttpClient(); XElement srcTree = new XElement("Deployment", new XAttribute(XNamespace.Xmlns + "i", ns1), new XElement("Name", ServiceName), new XElement("DeploymentSlot", "Production"), new XElement("Label", ServiceName), new XElement("RoleList", null) );   if (String.IsNullOrEmpty(VNETName) == false) { srcTree.Add(new XElement("VirtualNetworkName", VNETName)); }   if(DNSXML != null) { srcTree.Add(new XElement("DNS", new XElement("DNSServers", DNSXML))); }   XDocument deploymentXML = new XDocument(srcTree); ApplyNamespace(srcTree, ns);   deploymentXML.Descendants(ns + "RoleList").FirstOrDefault().Add(VMXML.Root);     String fixedXML = deploymentXML.ToString().Replace(" xmlns=\"\"", ""); HttpContent content = new StringContent(fixedXML); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml");   HttpResponseMessage responseMsg = await http.PostAsync(uri, content); if (responseMsg != null) { requestID = responseMsg.Headers.GetValues("x-ms-request-id").FirstOrDefault(); }   return requestID; } 2.3 Create Virtual Machine Request URI https://management.core.windows.net/<subscription-id>/services/hostedservices/<cloudservice-name>/deployments/<deployment-name>/roles <cloudservice-name> and <deployment-name> are provided as input from the previous steps Http Method POST (HTTP 1.1) Header x-ms-version: 2012-03-01 Content-Type: application/xml Body More details about request body (and other information) located here http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx C# code async public Task<String> NewAzureVM(String ServiceName, String VMName, XDocument VMXML) { String requestID = String.Empty;   String deployment = await GetAzureDeploymentName(ServiceName);   String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments/{2}/roles", _subscriptionid, ServiceName, deployment);   HttpClient http = GetHttpClient(); HttpContent content = new StringContent(VMXML.ToString()); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml"); HttpResponseMessage responseMsg = await http.PostAsync(uri, content); if (responseMsg != null) { requestID = responseMsg.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } return requestID; } (3) List Virtual Machines To list virtual machine hosted on windows azure subscription we have to loop over all hosted services to get its hosted virtual machines To do that we need to execute the following operations: listing hosted services listing hosted service Virtual machine 3.1 Listing Hosted Services Request URI https://management.core.windows.net/<subscription-id>/services/hostedservices HTTP Method GET (HTTP 1.1) Headers x-ms-version: 2012-03-01 Body None. More info about this HTTP request located here on this link http://msdn.microsoft.com/en-us/library/windowsazure/ee460781.aspx C# Code async private Task<List<XDocument>> GetAzureServices(String subscriptionid) { String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices ", subscriptionid); List<XDocument> services = new List<XDocument>();   HttpClient http = GetHttpClient();   Stream responseStream = await http.GetStreamAsync(uri);   if (responseStream != null) { XDocument xml = XDocument.Load(responseStream); var svcs = xml.Root.Descendants(ns + "HostedService"); foreach (XElement r in svcs) { XDocument vm = new XDocument(r); services.Add(vm); } }   return services; }  3.2 Listing Hosted Service Virtual Machines Request URI https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deployments/<deployment-name>/roles/<role-name> HTTP Method GET (HTTP 1.1) Headers x-ms-version: 2012-03-01 Body None. More info about this HTTP request here http://msdn.microsoft.com/en-us/library/windowsazure/jj157193.aspx C# Code async public Task<XDocument> GetAzureVM(String ServiceName, String VMName, String subscriptionid) { String deployment = await GetAzureDeploymentName(ServiceName); XDocument vmXML = new XDocument();   String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments/{2}/roles/{3}", subscriptionid, ServiceName, deployment, VMName);   HttpClient http = GetHttpClient(); Stream responseStream = await http.GetStreamAsync(uri); if (responseStream != null) { vmXML = XDocument.Load(responseStream); }   return vmXML; }  So the final method which can be used to list all virtual machines is: async public Task<XDocument> GetAzureVMs() { List<XDocument> services = await GetAzureServices(); XDocument vms = new XDocument(); vms.Add(new XElement("VirtualMachines")); ApplyNamespace(vms.Root, ns); foreach (var svc in services) { string ServiceName = svc.Root.Element(ns + "ServiceName").Value;   String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/{2}", _subscriptionid, ServiceName, "Production");   try { HttpClient http = GetHttpClient(); Stream responseStream = await http.GetStreamAsync(uri);   if (responseStream != null) { XDocument xml = XDocument.Load(responseStream); var roles = xml.Root.Descendants(ns + "RoleInstance"); foreach (XElement r in roles) { XElement svcnameel = new XElement("ServiceName", ServiceName); ApplyNamespace(svcnameel, ns); r.Add(svcnameel); // not part of the roleinstance vms.Root.Add(r); } } } catch (HttpRequestException http) { // no vms with cloud service } } return vms; }  (4) Restart Virtual Machine Request URI https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deployments/<deployment-name>/roles/<role-name>/Operations HTTP Method POST (HTTP 1.1) Headers x-ms-version: 2012-03-01 Content-Type: application/xml Body <RestartRoleOperation xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <OperationType>RestartRoleOperation</OperationType> </RestartRoleOperation>  More details about this http request here http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx  C# Code async public Task<String> RebootVM(String ServiceName, String RoleName) { String requestID = String.Empty;   String deployment = await GetAzureDeploymentName(ServiceName); String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments/{2}/roleInstances/{3}/Operations", _subscriptionid, ServiceName, deployment, RoleName);   HttpClient http = GetHttpClient();   XElement srcTree = new XElement("RestartRoleOperation", new XAttribute(XNamespace.Xmlns + "i", ns1), new XElement("OperationType", "RestartRoleOperation") ); ApplyNamespace(srcTree, ns);   XDocument CSXML = new XDocument(srcTree); HttpContent content = new StringContent(CSXML.ToString()); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml");   HttpResponseMessage responseMsg = await http.PostAsync(uri, content); if (responseMsg != null) { requestID = responseMsg.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } return requestID; }  (5) Delete Virtual Machine You can delete your hosted virtual machine by deleting its deployment, but I prefer to delete its hosted service also, so you can easily manage your virtual machines from code 5.1 Delete Deployment Request URI https://management.core.windows.net/< subscription-id >/services/hostedservices/< service-name >/deployments/<Deployment-Name> HTTP Method DELETE (HTTP 1.1) Headers x-ms-version: 2012-03-01 Body None. C# code async public Task<HttpResponseMessage> DeleteDeployment( string deploymentName) { string xml = string.Empty; String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments/{2}", _subscriptionid, deploymentName, deploymentName); HttpClient http = GetHttpClient(); HttpResponseMessage responseMessage = await http.DeleteAsync(uri); return responseMessage; }  5.2 Delete Hosted Service Request URI https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name> HTTP Method DELETE (HTTP 1.1) Headers x-ms-version: 2012-03-01 Body None. C# code async public Task<HttpResponseMessage> DeleteService(string serviceName) { string xml = string.Empty; String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}", _subscriptionid, serviceName); Log.Info("Windows Azure URI (http DELETE verb): " + uri, typeof(VMManager)); HttpClient http = GetHttpClient(); HttpResponseMessage responseMessage = await http.DeleteAsync(uri); return responseMessage; }  And the following is the method which can used to delete both of deployment and service async public Task<string> DeleteVM(string vmName) { string responseString = string.Empty;   // as a convention here in this post, a unified name used for service, deployment and VM instance to make it easy to manage VMs HttpClient http = GetHttpClient(); HttpResponseMessage responseMessage = await DeleteDeployment(vmName);   if (responseMessage != null) {   string requestID = responseMessage.Headers.GetValues("x-ms-request-id").FirstOrDefault(); OperationResult result = await PollGetOperationStatus(requestID, 5, 120); if (result.Status == OperationStatus.Succeeded) { responseString = result.Message; HttpResponseMessage sResponseMessage = await DeleteService(vmName); if (sResponseMessage != null) { OperationResult sResult = await PollGetOperationStatus(requestID, 5, 120); responseString += sResult.Message; } } else { responseString = result.Message; } } return responseString; }  Note: This article is subject to be updated Hisham  References Advanced Windows Azure IaaS – Demo Code Windows Azure Service Management REST API Reference Introduction to the Azure Platform Representational state transfer Asynchronous Programming with Async and Await (C# and Visual Basic) HttpClient Class

    Read the article

  • Using HttpClient with the RightScale API

    - by Ameer Deen
    I'm trying to use the WCF Rest Starter Kit with the RightScale's Login API which seems fairly simple to use. Edit - Here's a blog entry I wrote on using Powershell to consume the API. Edit - Created a generic .NET wrapper for the RightScale API - NRightAPI It's exactly as simple as it looks while using CURL. In order for me to obtain a login cookie all I need to do is: curl -v -c rightcookie -u username:password "https://my.rightscale.com/api/acct/accountid/login?api_version=1.0" And I receive the following cookie: HTTP/1.1 204 No Content Date: Fri, 25 Dec 2009 12:29:24 GMT Server: Mongrel 1.1.3 Status: 204 No Content X-Runtime: 0.06121 Content-Type: text/html; charset=utf-8 Content-Length: 0 Cache-Control: no-cache Added cookie _session_id="488a8d9493579b9473fbcfb94b3a7b8e5e3" for domain my.rightscale.com, path /, expire 0 Set-Cookie: _session_id=488a8d9493579b9473fbcfb94b3a7b8e5e3; path=/; secure Vary: Accept-Encoding However, when I use the following C# code: HttpClient http = new HttpClient("https://my.rightscale.com/api/accountid/login?api_version=1.0"); http.TransportSettings.UseDefaultCredentials = false; http.TransportSettings.MaximumAutomaticRedirections = 0; http.TransportSettings.Credentials = new NetworkCredential("username", "password"); Console.WriteLine(http.Get().Content.ReadAsString()); Instead of a HTTP 204, I get a redirect: You are being <a> href="https://my.rightscale.com/dashboard"redirected <a> How do I get the WCF REST starter kit working with the RighScale API ?

    Read the article

  • Http authentication with apache httpcomponents

    - by matdan
    Hi, I am trying to develop a java http client with apache httpcomponents 4.0.1. This client calls the page "https://myHost/myPage". This page is protected on the server by a JNDIRealm with a login form authentication, so when I try to get https://myHost/myPage I get a login page. I tried to bypass it unsuccessfully with the following code : //I set my proxy HttpHost proxy = new HttpHost("myProxyHost", myProxyPort); //I add supported schemes SchemeRegistry supportedSchemes = new SchemeRegistry(); supportedSchemes.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); supportedSchemes.register(new Scheme("https", SSLSocketFactory .getSocketFactory(), 443)); // prepare parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes); DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); //I add my authentication information httpclient.getCredentialsProvider().setCredentials( new AuthScope("myHost/myPage", 443), new UsernamePasswordCredentials("username", "password")); HttpHost host = new HttpHost("myHost", 443, "https"); HttpGet req = new HttpGet("/myPage"); //show the page ResponseHandler<String> responseHandler = new BasicResponseHandler(); String rsp = httpClient.execute(host, req, responseHandler); System.out.println(rsp); When I run this code, I always get the login page, not myPage. How can I apply my credential parameters to avoid this login form? Any help would be fantastic

    Read the article

  • Jar dependencies to use jetty httpclient

    - by Alfred
    Hi all, I want to use the jetty httpclient(in netbeans) but have the least number of jar dependencies. I know I can import all jars from the jetty lib folder to my project but I would like to know what the minimum number of dependencies are and how you did find this out? Our there tools to find jar dependencies?

    Read the article

  • Android:HttpClient does not run in Android 4.0 API

    - by user1635564
    I have written the code it works on Android 2.2 API but it does not work on Android 4.0 String url = textUrl.getText().toString(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); try { HttpResponse response = client.execute(request); textResult.setText(HttpHelper.request(response)); } catch (Exception e) { // TODO: handle exception textResult.setText("Failed"); }

    Read the article

  • org.apache.http.impl.cookie.BasicClientCookie not serializable???

    - by Misha Koshelev
    Dear All: I am quite confused... I am reading here and BasicClientCookie clearly implements Serializable per JavaDoc: http://hc.apache.org/httpcomponents-client/httpclient/apidocs/org/apache/http/impl/cookie/BasicClientCookie.html However, my simple Groovy script: #!/usr/bin/env groovy @Grapes( @Grab(group='org.apache.httpcomponents', module='httpclient', version='4.0.1') ) import org.apache.http.impl.cookie.BasicClientCookie import java.io.File def cookie=new BasicClientCookie("name","value") println cookie instanceof Serializable def f=new File("/tmp/test") f.withObjectOutputStream() { oos-> oos.writeObject(cookie) } outputs: false Caught: java.io.NotSerializableException: org.apache.http.impl.cookie.BasicClientCookie at t$_run_closure1.doCall(t.groovy:12) at t.run(t.groovy:11) I have checked and I have no other versions of HttpClient anywhere in classpath (if I take Grapes statement out it cannot find file). Thank you! Misha Koshelev

    Read the article

  • IO Exception on invoking execute() method of HttpGet class

    - by AndroidNoob
    Why I'm getting IOException in this peace of code? Thanks. HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://www.google.com/"); HttpResponse response; try { response = httpclient.execute(httpget); } catch (ClientProtocolException e) { Toast.makeText(this, "ClientProtocolEx", Toast.LENGTH_LONG).show(); e.printStackTrace(); } catch (IOException e) { Toast.makeText(this, "IOEx", Toast.LENGTH_LONG).show(); e.printStackTrace(); }

    Read the article

  • WCF HttpClient Error calling a RESTful WCF Service - Cannot write more bytes to the buffer than the configured maximum buffer size: 65536

    - by Justin Hoffman
    Using the HttpClient API from wcf.codeplex.com, you may encounter this error if respones are too large.   Cannot write more bytes to the buffer than the configured maximum buffer size: 65536 In order to increase the size of the Response Buffer, just increase the MaxReseponseContentBufferSize as shown below. Increase it to something larger than the default: 65536 depending on your response sizes. var client = new HttpClient { MaxResponseContentBufferSize = 196608, BaseAddress = new Uri("http://myservice/service1/") };

    Read the article

  • java client program to send digest authentication request using HttpClient API

    - by Rajesh
    I have restlet sample client program which sends the digest request. Similar to this I need java client program which sends a digest request using HttpClient api. Can anybody send me sample code. Thanks in advance. Reference reference = new Reference("http://localhost:8092/authenticate"); Client client = new Client(Protocol.HTTP); Request request = new Request(Method.GET, reference); Response response = client.handle(request); System.out.println("response: "+response.getStatus()); Form form = new Form(); form.add("username", "rajesh"); form.add("uri", reference.getPath()); // Loop over the challengeRequest objects sent by the server. for (ChallengeRequest challengeRequest : response .getChallengeRequests()) { // Get the data from the server's response. if (ChallengeScheme.HTTP_DIGEST .equals(challengeRequest.getScheme())) { Series<Parameter> params = challengeRequest.getParameters(); form.add(params.getFirst("nonce")); form.add(params.getFirst("realm")); form.add(params.getFirst("domain")); form.add(params.getFirst("algorithm")); form.add(params.getFirst("qop")); } } // Compute the required data String a1 = Engine.getInstance().toMd5( "rajesh" + ":" + form.getFirstValue("realm") + ":" + "rajesh"); String a2 = Engine.getInstance().toMd5( request.getMethod() + ":" + form.getFirstValue("uri")); form.add("response", Engine.getInstance().toMd5( a1 + ":" + form.getFirstValue("nonce") + ":" + a2)); ChallengeResponse challengeResponse = new ChallengeResponse( ChallengeScheme.HTTP_DIGEST, "", ""); challengeResponse.setCredentialComponents(form); // Send the completed request request.setChallengeResponse(challengeResponse); response = client.handle(request); // Should be 200. System.out.println(response.getStatus());

    Read the article

  • posting nutch data into a BASIC auth secured Solr instance

    - by mlathe
    Hi. I've secured a solr instance using BASIC auth, kind of how it is shown here: http://blog.comtaste.com/2009/02/securing_your_solr_server_on_t.html Now i'm trying to update my batch processes to push data into the authenticated instance. The ones using "curl" are easy, but i also have a Nutch crawl that uses the "solrindex" command to push data into Solr. When i do that i get this error: 2010-02-22 12:09:28,226 INFO auth.AuthChallengeProcessor - basic authentication scheme selected 2010-02-22 12:09:28,229 INFO httpclient.HttpMethodDirector - No credentials available for BASIC 'Tomcat Manager Application'@ninja:5500 2010-02-22 12:09:28,236 WARN mapred.LocalJobRunner - job_local_0001 org.apache.solr.common.SolrException: Unauthorized Unauthorized request: http://ninja:5500/solr/foo/update?wt=javabin&version=2.2 at org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.request(CommonsHttpSolrServer.java:343) at org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.request(CommonsHttpSolrServer.java:183) at org.apache.solr.client.solrj.request.UpdateRequest.process(UpdateRequest.java:217) at org.apache.solr.client.solrj.SolrServer.add(SolrServer.java:48) at org.apache.nutch.indexer.solr.SolrWriter.close(SolrWriter.java:69) at org.apache.nutch.indexer.IndexerOutputFormat$1.close(IndexerOutputFormat.java:48) at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:447) at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:170) 2010-02-22 12:09:29,134 FATAL solr.SolrIndexer - SolrIndexer: java.io.IOException: Job failed! at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:1232) at org.apache.nutch.indexer.solr.SolrIndexer.indexSolr(SolrIndexer.java:73) at org.apache.nutch.indexer.solr.SolrIndexer.run(SolrIndexer.java:95) at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65) at org.apache.nutch.indexer.solr.SolrIndexer.main(SolrIndexer.java:104) Apparently nutch uses SolrJ to push the content, and after going through the solrj code, it's clear that it uses commons-httpclient without providing a way to set the credentials. Here are my question(s) Is this possible to do? ie push from nutch into a BASIC auth secured Solr instance? Is it possible to tell commons-httpclient about a credential without explicitly doing an _httpclient.getState().setCredentials(...)? Anyother ideas? One idea i had was to use an IPfiltering Valve for just the "update" Solr webservices. That would mean you could only make an update call from certain nodes. Thanks

    Read the article

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