EzDevInfo.com

httpclient

'httpclient' gives something like the functionality of libwww-perl (LWP) in Ruby. nahi/httpclient · GitHub 'httpclient' gives something like the functionality of libwww-perl (lwp) in ruby.

Accepting a certificate for HTTPs on Android

I'm trying to make Https connections on the Android phones, using HttpClient. Trouble is that since the certificate isn't signed I keep getting "javax.net.ssl.SSLException: Not trusted server certificate".

Now I've seen a bunch of solutions where you simply accept all certificates, but what if I want to ask the user? I want to get a dialog similar to that of the browser, letting the user decide to continue or not.

Preferably I'd like to use the same certificatestore as the browser. Any ideas?


Source: (StackOverflow)

Preemptive Basic authentication with Apache HttpClient 4

Is there an easier way to setup the http client for preemptive basic authentication than what described here?
In previous version (3.x) it used to be a simple method call (eg, httpClient.getParams().setAuthenticationPreemptive(true)).
The main thing I want to avoid is adding the BasicHttpContext to each method I execute.


Source: (StackOverflow)

Advertisements

Trusting all certificates using HttpClient over HTTPS

Recently posted a question regarding the HttpClient over Https (found here). I've made some headway, but I've run into new issues. As with my last problem, I can't seem to find an example anywhere that works for me. Basically, I want my client to accept any certificate (because I'm only ever pointing to one server) but I keep getting a javax.net.ssl.SSLException: Not trusted server certificate exception.

So this is what I have:

public void connect() throws A_WHOLE_BUNCH_OF_EXCEPTIONS {

    HttpPost post = new HttpPost(new URI(PROD_URL));
    post.setEntity(new StringEntity(BODY));

    KeyStore trusted = KeyStore.getInstance("BKS");
    trusted.load(null, "".toCharArray());
    SSLSocketFactory sslf = new SSLSocketFactory(trusted);
    sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme ("https", sslf, 443));
    SingleClientConnManager cm = new SingleClientConnManager(post.getParams(),
            schemeRegistry);

    HttpClient client = new DefaultHttpClient(cm, post.getParams());
    HttpResponse result = client.execute(post);
}

And here's the error I'm getting:

W/System.err(  901): javax.net.ssl.SSLException: Not trusted server certificate
W/System.err(  901):    at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:360)
W/System.err(  901):    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:92)
W/System.err(  901):    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:321)
W/System.err(  901):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:129)
W/System.err(  901):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
W/System.err(  901):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
W/System.err(  901):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
W/System.err(  901):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
W/System.err(  901):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
W/System.err(  901):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
W/System.err(  901):    at me.harrisonlee.test.ssl.MainActivity.connect(MainActivity.java:129)
W/System.err(  901):    at me.harrisonlee.test.ssl.MainActivity.access$0(MainActivity.java:77)
W/System.err(  901):    at me.harrisonlee.test.ssl.MainActivity$2.run(MainActivity.java:49)
W/System.err(  901): Caused by: java.security.cert.CertificateException: java.security.InvalidAlgorithmParameterException: the trust anchors set is empty
W/System.err(  901):    at org.apache.harmony.xnet.provider.jsse.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:157)
W/System.err(  901):    at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:355)
W/System.err(  901):    ... 12 more
W/System.err(  901): Caused by: java.security.InvalidAlgorithmParameterException: the trust anchors set is empty
W/System.err(  901):    at java.security.cert.PKIXParameters.checkTrustAnchors(PKIXParameters.java:645)
W/System.err(  901):    at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:89)
W/System.err(  901):    at org.apache.harmony.xnet.provider.jsse.TrustManagerImpl.<init>(TrustManagerImpl.java:89)
W/System.err(  901):    at org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl.engineGetTrustManagers(TrustManagerFactoryImpl.java:134)
W/System.err(  901):    at javax.net.ssl.TrustManagerFactory.getTrustManagers(TrustManagerFactory.java:226)
W/System.err(  901):    at org.apache.http.conn.ssl.SSLSocketFactory.createTrustManagers(SSLSocketFactory.java:263)
W/System.err(  901):    at org.apache.http.conn.ssl.SSLSocketFactory.<init>(SSLSocketFactory.java:190)
W/System.err(  901):    at org.apache.http.conn.ssl.SSLSocketFactory.<init>(SSLSocketFactory.java:216)
W/System.err(  901):    at me.harrisonlee.test.ssl.MainActivity.connect(MainActivity.java:107)
W/System.err(  901):    ... 2 more

Source: (StackOverflow)

How to handle invalid SSL certificates with Apache HttpClient?

I know, there are many different questions and so many answers about this problem... But I can't understand...

I have: ubuntu-9.10-desktop-amd64 + NetBeans6.7.1 installed "as is" from off. rep. I need connecting to some site over the HTTPS. For this I use Apache's HttpClient.

From tutorial I read:

"Once you have JSSE correctly installed, secure HTTP communication over SSL should be as
simple as plain HTTP communication." And some example:

HttpClient httpclient = new HttpClient();
GetMethod httpget = new GetMethod("https://www.verisign.com/"); 
try { 
  httpclient.executeMethod(httpget);
  System.out.println(httpget.getStatusLine());
} finally {
  httpget.releaseConnection();
}

By now, I write this:

HttpClient client = new HttpClient();

HttpMethod get = new GetMethod("https://mms.nw.ru");
//get.setDoAuthentication(true);

try {
    int status = client.executeMethod(get);
    System.out.println(status);

    BufferedInputStream is = new BufferedInputStream(get.getResponseBodyAsStream());
    int r=0;byte[] buf = new byte[10];
    while((r = is.read(buf)) > 0) {
        System.out.write(buf,0,r);
    }

} catch(Exception ex) {
    ex.printStackTrace();
}

As a result I have a set of errors:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1627)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:204)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:198)
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:994)
        at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:142)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:533)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:471)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:904)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1132)
        at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:643)
        at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:78)
        at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
        at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
        at org.apache.commons.httpclient.HttpConnection.flushRequestOutputStream(HttpConnection.java:828)
        at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2116)
        at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
        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)
        at simpleapachehttp.Main.main(Main.java:41)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:302)
        at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:205)
        at sun.security.validator.Validator.validate(Validator.java:235)
        at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:147)
        at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:230)
        at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:270)
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:973)
        ... 17 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:191)
        at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:255)
        at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:297)
        ... 23 more

What have I to do to create simplest SSL connection? (Probably without KeyManager and Trust manager etc. while.)


Source: (StackOverflow)

Exception using HttpRequest.execute(): Invalid use of SingleClientConnManager: connection still allocated

I'm using google-api-client-java 1.2.1-alpha to execute a POST request, and am getting the following stacktrace when I execute() the HttpRequest.

It happens immediately after I catch and ignore a 403 error from a previous POST to the same URL, and re-used the transport for the subsequent request. (It's in a loop inserting multiple entries to the same ATOM feed).

Is there something I should be doing to 'clean up' after a 403?

Exception in thread "main" java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
    at org.apache.http.impl.conn.SingleClientConnManager.getConnection(SingleClientConnManager.java:199)
    at org.apache.http.impl.conn.SingleClientConnManager$1.getConnection(SingleClientConnManager.java:173)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:390)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
    at com.google.api.client.apache.ApacheHttpRequest.execute(ApacheHttpRequest.java:47)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:207)
    at au.com.machaira.pss.gape.RedirectHandler.execute(RedirectHandler.java:38)
    at au.com.machaira.pss.gape.ss.model.records.TableEntry.executeModification(TableEntry.java:81)

Why would the code below me be trying to acquire a new connection?


Source: (StackOverflow)

HttpGet with HTTPS : SSLPeerUnverifiedException

Using HttpClient, I receive the following error when attempting to communicate over HTTPS:

Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated.

Here is my code:

URI loginUri = new URI("https://myUrl.asp");

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet( loginUri );
HttpResponse response = httpclient.execute( httpget );

How do I suppress or remove this error?


Source: (StackOverflow)

HttpDelete with body

I'm attempting to use an HttpDelete object to invoke a web service's delete method. The web service's code parses JSON from the message's body. However, I'm failing to understand how to add a body to an HttpDelete object. Is there a way to do this?

With HttpPut and HttpPost, I call the setEntity method and pass in my JSON. There doesn't appear to be any such method for HttpDelete.

If there is no way to set a body for an HttpDelete object, could you please link me to a resource that uses a super class of HttpDelete such that I can set the method (delete) and set a body. I know that isn't ideal, but at this point I can't alter the web service.


Source: (StackOverflow)

Android HttpClient and HTTPS

I'm new to implementing HTTPS connections in Android. Essentially, I'm trying to connect to a server using the org.apache.http.client.HttpClient. I believe, at some point, I'll need to access the application's keystore in order to authorize my client with a private key. But, for the moment, I'm just trying to connect and see what happens; I keep getting an HTTP/1.1 400 Bad Request error.

I can't seem to make heads or tails of this despite many examples (none of them seem to work for me). My code looks like this (the BODY constant is XmlRPC):

 private void connect() throws IOException, URISyntaxException{

    HttpPost post     = new HttpPost(new URI(PROD_URL));
    HttpClient client = new DefaultHttpClient();

    post.setEntity(new StringEntity(BODY));
    HttpResponse result = client.execute(post);

    Log.d("MainActivity", result.getStatusLine().toString());

}

So, pretty simple. Let me know if anyone out there has any advice. Thanks!


Source: (StackOverflow)

HttpClient 4 - how to capture last redirect URL

I have rather simple HttpClient 4 code that calls HttpGet to get HTML output. The HTML returns with scripts and image locations all set to local (e.g. <img src="/images/foo.jpg"/>) so I need calling URL to make these into absolute (<img src="http://foo.com/images/foo.jpg"/>) Now comes the problem - during the call there may be one or two 302 redirects so the original URL is no longer reflects the location of HTML.

How do I get the latest URL of the returned content given all the redirects I may (or may not) have?

I looked at HttpGet#getAllHeaders() and HttpResponse#getAllHeaders() - couldn't find anything.

Edited: HttpGet#getURI() returns original calling address


Source: (StackOverflow)

HTTP Post requests using HttpClient take 2 seconds, why?

Update: Found the answer myself, see below :-)

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?


Source: (StackOverflow)

How to add json to the body of an http post in java

I'm trying to post some JSON data in java for an Android app I'm working on. Is the below valid or do I need to push the JSON string in a different way?

HttpPost httpost = new HttpPost("http://test.localhost");
httpost.setEntity(new StringEntity("{\"filters\":true}"));
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
//... other java code to execute the apache httpclient

Thank you in advance


Source: (StackOverflow)

How do I manage cookies with HttpClient in Android and/or Java?

I am trying to login to a site and maintain that session/cookie so that the server will recognize my login, but I am struggling to figure out a way of extracting the cookie from the response and setting into a request to maintain my login. I'm wondering if I should go about taking the header "Set-Cookie" or using a CookieStore. Any help is greatly appreciated. Here is my code that I have, with comments where I think the getHeader/getCookie methods would go.

public class Http
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request;
HttpEntity entity;
HttpResponse response;
HttpPost post;
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();

public static void setContext()
{
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

public static void getPage(String url) throws Exception
{
    request = new HttpGet(url);
    response = client.execute(request, localContext);
    PARSER.preParse(url, response);
}

public static HttpResponse postPage(List<NameValuePair> params, String host, String action) throws Exception
{
    post = new HttpPost(host + action);
    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

    response = client.execute(post, localContext);

    entity = response.getEntity();
    if(entity != null)
    {
        entity.consumeContent();
    }

    return response;
}


public void destoyHttp()
{
    client.getConnectionManager().shutdown();
}
}

In hopes of others better understanding my confusion am adding code that I know DOES work and maintains a session but when I tried to move the code into my actual application it broke somewhere down the line.

public class HttpClientTest extends Activity{

DefaultHttpClient client = new DefaultHttpClient();
HttpGet request;
HttpEntity entity;
List<Cookie> cookies;
HttpResponse response;
HttpPost post;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        getRequest();
    } catch (Exception e) {
        Log.d("My Activity", "Failed");
        e.printStackTrace();
    }
}

public void getRequest() throws Exception
{
    final String TAG = "MyActivity";
    request = new HttpGet("http://gc.gamestotal.com/i.cfm?p=login&se=4");
    response = client.execute(request);

    String action = "i.cfm?&1028&p=login&se=4";
    String yourServer = "http://gc.gamestotal.com/";
    post = new HttpPost(yourServer + action);

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("nic", "myusername"));
    params.add(new BasicNameValuePair("password", "mypassword"));
    params.add(new BasicNameValuePair("server", "4"));

    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));


    response = client.execute(post);
    entity = response.getEntity();

    if(entity != null){
        entity.consumeContent();
    }

    request = new HttpGet("http://gc.gamestotal.com/i.cfm?f=com_empire&cm=3");

    response = client.execute(request);

    if(entity != null)
    {
        entity.consumeContent();
    }    

}

}

I know for a fact it works, and you can see that in this code I consumeContent() but adding that to the top code didn't seem to make a difference so I left it out. Any Ideas?

Edit: I am still unable to get the code working in keeping a session going. I am posting the cookies from my current code, along with the cookies of the second code that is working. Perhaps someone will notice an issue, I certainly do not.

08-31 06:53:50.318: VERBOSE/SFGC(496): - [version: 0][name: CFID][value: 26651316][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]
08-31 06:53:50.329: VERBOSE/SFGC(496): - [version: 0][name: CFTOKEN][value: 96917381][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]
08-31 06:53:50.329: VERBOSE/SFGC(496): - [version: 0][name: CFCLIENT_SFGC_106Y][value: CFTOKEN2%3D735125416524430%23COUNTRY%3D56%23DOWNLOADFLAG%3D0%23OCHAT%3D1%23PM%5FDATE%3D%7Bts+%272010%2D08%2D31+14%3A53%3A45%27%7D%23REGION%3D3%23SCREEN%3D800%23S%5FGC%5FIMAGELOC%3Di%2Fw%2F%23TIMEZONE%3D%2D600%23][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]
08-31 06:53:50.339: VERBOSE/SFGC(496): - [version: 0][name: CFGLOBALS][value: HITCOUNT%3D2%23LASTVISIT%3D%7Bts+%272010%2D08%2D31+14%3A53%3A45%27%7D%23TIMECREATED%3D%7Bts+%272010%2D08%2D31+14%3A53%3A39%27%7D%23][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]

08-31 06:53:51.938: VERBOSE/SFGC(496): - [version: 0][name: CFID][value: 26651316][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]
08-31 06:53:51.938: VERBOSE/SFGC(496): - [version: 0][name: CFTOKEN][value: 96917381][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]
08-31 06:53:51.938: VERBOSE/SFGC(496): - [version: 0][name: CFCLIENT_SFGC_106Y][value: CFTOKEN2%3D735125416524430%23COUNTRY%3D56%23DOWNLOADFLAG%3D0%23OCHAT%3D1%23PM%5FDATE%3D%7Bts+%272010%2D08%2D31+14%3A53%3A45%27%7D%23REGION%3D3%23SCREEN%3D800%23S%5FGC%5FIMAGELOC%3Di%2Fw%2F%23TIMEZONE%3D%2D600%23][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]
08-31 06:53:51.948: VERBOSE/SFGC(496): - [version: 0][name: CFGLOBALS][value: HITCOUNT%3D3%23LASTVISIT%3D%7Bts+%272010%2D08%2D31+14%3A53%3A46%27%7D%23TIMECREATED%3D%7Bts+%272010%2D08%2D31+14%3A53%3A39%27%7D%23][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]


08-31 06:52:41.628: DEBUG/MyActivity(469): - [version: 0][name: CFID][value: 26651274][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]
08-31 06:52:41.638: DEBUG/MyActivity(469): - [version: 0][name: CFTOKEN][value: 58361320][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]
08-31 06:52:41.638: DEBUG/MyActivity(469): - [version: 0][name: CFCLIENT_SFGC_106Y][value: CFTOKEN2%3D735125815099420%23COUNTRY%3D56%23DOWNLOADFLAG%3D0%23OCHAT%3D1%23PM%5FDATE%3D%7Bts+%272010%2D08%2D31+14%3A52%3A36%27%7D%23REGION%3D3%23SCREEN%3D800%23S%5FGC%5FIMAGELOC%3Di%2Fw%2F%23TIMEZONE%3D%2D600%23][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]
08-31 06:52:41.648: DEBUG/MyActivity(469): - [version: 0][name: CFGLOBALS][value: HITCOUNT%3D2%23LASTVISIT%3D%7Bts+%272010%2D08%2D31+14%3A52%3A36%27%7D%23TIMECREATED%3D%7Bts+%272010%2D08%2D31+14%3A52%3A33%27%7D%23][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]

08-31 06:52:44.138: DEBUG/MyActivity(469): - [version: 0][name: CFID][value: 26651274][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]
08-31 06:52:44.138: DEBUG/MyActivity(469): - [version: 0][name: CFTOKEN][value: 58361320][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]
08-31 06:52:44.138: DEBUG/MyActivity(469): - [version: 0][name: CFCLIENT_SFGC_106Y][value: CFTOKEN2%3D735125815099420%23COUNTRY%3D56%23DOWNLOADFLAG%3D0%23OCHAT%3D1%23PM%5FDATE%3D%7Bts+%272010%2D08%2D31+14%3A52%3A36%27%7D%23REGION%3D3%23SCREEN%3D800%23S%5FGC%5FIMAGELOC%3Di%2Fw%2F%23TIMEZONE%3D%2D600%23][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]
08-31 06:52:44.138: DEBUG/MyActivity(469): - [version: 0][name: CFGLOBALS][value: HITCOUNT%3D4%23LASTVISIT%3D%7Bts+%272010%2D08%2D31+14%3A52%3A38%27%7D%23TIMECREATED%3D%7Bts+%272010%2D08%2D31+14%3A52%3A33%27%7D%23][domain: gc.gamestotal.com][path: /][expiry: Sun Sep 27 00:00:00 GMT+00:00 2037]

Source: (StackOverflow)

How do I set up HttpContent for my HttpClient PostAsync second parameter?

public static async Task<string> GetData(string url, string data)
{
    UriBuilder fullUri = new UriBuilder(url);

    if (!string.IsNullOrEmpty(data))
        fullUri.Query = data;

    HttpClient client = new HttpClient();

    HttpResponseMessage response = await client.PostAsync(new Uri(url), /*expects HttpContent*/);

    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    response.EnsureSuccessStatusCode();
    string responseBody = await response.Content.ReadAsStringAsync();

    return responseBody;
}

The PostAsync takes another parameter that needs to be HttpContent.

How do I set up an HttpContent? There Is no documentation anywhere that works for Windows Phone 8.

If I do GetAsync, it works great! but it needs to be POST with the content of key="bla", something="yay"

//EDIT

Thanks so much for the answer... This works well, but still a few unsures here:

    public static async Task<string> GetData(string url, string data)
    {
        data = "test=something";

        HttpClient client = new HttpClient();
        StringContent queryString = new StringContent(data);

        HttpResponseMessage response = await client.PostAsync(new Uri(url), queryString );

        //response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();

        return responseBody;
    }

The data "test=something" I assumed would pick up on the api side as post data "test", evidently it does not. On another matter, I may need to post entire objects/arrays through post data, so I assume json will be best to do so. Any thoughts on how I get post data through?

Perhaps something like:

class SomeSubData
{
    public string line1 { get; set; }
    public string line2 { get; set; }
}

class PostData
{
    public string test { get; set; }
    public SomeSubData lines { get; set; }
}

PostData data = new PostData { 
    test = "something",
    lines = new SomeSubData {
        line1 = "a line",
        line2 = "a second line"
    }
}
StringContent queryString = new StringContent(data); // But obviously that won't work

Source: (StackOverflow)

How to upload a file using Java HttpClient library working with PHP

I want to write Java application that will upload a file to the Apache server with PHP. The Java code uses Jakarta HttpClient library version 4.0 beta2:

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class PostFile {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost:9002/upload.php");
    File file = new File("c:/TRASH/zaba_1.jpg");

    FileEntity reqEntity = new FileEntity(file, "binary/octet-stream");

    httppost.setEntity(reqEntity);
    reqEntity.setContentType("binary/octet-stream");
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
}

The PHP file upload.php is very simple:

<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
  echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
  move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']);
} else {
  echo "Possible file upload attack: ";
  echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
  print_r($_FILES);
}
?>

Reading the response I get the following result:

executing request POST http://localhost:9002/upload.php HTTP/1.1
HTTP/1.1 200 OK
Possible file upload attack: filename ''.
Array
(
)

So the request was successful, I was able to communicate with server, however PHP didn't notice the file - the method is_uploaded_file returned false and $_FILES variable is empty. I have no idea why this might happend. I have tracked HTTP response and request and they look ok:
request is:

POST /upload.php HTTP/1.1
Content-Length: 13091
Content-Type: binary/octet-stream
Host: localhost:9002
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.0-beta2 (java 1.5)
Expect: 100-Continue

˙Ř˙ŕ..... the rest of the binary file...

and response:

HTTP/1.1 100 Continue

HTTP/1.1 200 OK
Date: Wed, 01 Jul 2009 06:51:57 GMT
Server: Apache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5 mod_jk/1.2.26
X-Powered-By: PHP/5.2.5
Content-Length: 51
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html

Possible file upload attack: filename ''.Array
(
)

I was testing this both on the local windows xp with xampp and remote Linux server. I have also tried to use previous version of HttpClient - version 3.1 - and the result was even more unclear, is_uploaded_file returned false, however $_FILES array was filled with proper data.


Source: (StackOverflow)

Android HttpClient persistent cookies

UPDATE: This question and its answers should no longer be recommended to anyone reading this. Android no-longer recommends HttpClient (read: deprecated), and instead recommends HttpUrlConnection. A good example of libraries to use now, are Retrofit and OkHttp. In the context of this question, cookies can be saved, stored and delivered with subsequent queries. This is not handled transparently. With OkHttp you can use Interceptors.

I have an Android application with multiple intents.

The first intent is a login form, subsequent intents rely on cookies provided from the login process.

The problem that I am having is that cookies do not appear to be persisting across the intents. I am creating new HttpClients in each intent (I initially tried to Parcelable transmit it across to each intent, which did not work so well).

Does anyone have any tips for making cookies persist across intents?


Source: (StackOverflow)