Http Post connection in SDK-1.0

Problems with WiFi, SQLite ,Bluetooth, WiMax, Proxies, etc...

Http Post connection in SDK-1.0

Postby Nemat » Mon Sep 29, 2008 9:56 am

Hi,
I am using Android SDK-1.0.I was able to make Http post connection with server in SDK-0.9.How can this be done using new SDK?

Thanks in advance
Nemat
Experienced Developer
Experienced Developer
 
Posts: 62
Joined: Thu Aug 21, 2008 3:16 pm
Location: Jaipur

Top

Postby ninor » Mon Sep 29, 2008 10:25 am

This Http thing has changed a little bit.
Here's the new location of the library (and possibly there are some internal changes):
http://code.google.com/android/reference/org/apache/http/impl/package-summary.html
User avatar
ninor
Moderator
Moderator
 
Posts: 180
Joined: Thu Aug 14, 2008 6:30 pm
Location: Barcelona, Spain

Postby Nemat » Mon Sep 29, 2008 11:39 am

Thanks ninor for your reply.

But I got error in implementing EventHandler interface and android.net.http.RequestQueue class.


Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. public void go(Map<String,String> variables){
  2.  
  3.        
  4.  
  5.        
  6.  
  7.        MyEventHandler myEvH = new MyEventHandler(this);
  8.  
  9.    
  10.  
  11.        
  12.  
  13.         android.net.http.RequestQueue rQueue = new RequestQueue(this);        
  14.  
  15.  
  16.  
  17.        
  18.  
  19.         Map<String, String> headers = new HashMap<String, String>();
  20.  
  21.      
  22.  
  23.         headers.put("Content-Type", "application/x-www-form-urlencoded");
  24.  
  25.        
  26.  
  27.                String variablesURL;
  28.  
  29.         if(variables != null && variables.size() > 0){
  30.  
  31.              try {
  32.  
  33.                   StringBuilder b = new StringBuilder();
  34.  
  35.                   Set<String> keys = variables.keySet();
  36.  
  37.                   // Iterate over each variable you want and append it to our variablesURL variable
  38.  
  39.                   for(Iterator<String> i = keys.iterator();;){
  40.  
  41.                        String key = i.next();
  42.  
  43.                        b.append(key);
  44.  
  45.                        b.append("=");
  46.  
  47.                        b.append(URLEncoder.encode(variables.get(key), "UTF-8"));
  48.  
  49.                        
  50.  
  51.                        // Minor speed optimization so that i.hasNext() is only called once (instead of in the for loop).
  52.  
  53.                        if(i.hasNext()){
  54.  
  55.                             b.append("&");
  56.  
  57.                        } else {
  58.  
  59.                             break;
  60.  
  61.                        }
  62.  
  63.                   }
  64.  
  65.                   variablesURL = b.toString();
  66.  
  67.              } catch (UnsupportedEncodingException e) {
  68.  
  69.                   Log.e("HTTP_Request", "Unsupported Encoding Exception");
  70.  
  71.                   return;
  72.  
  73.              }
  74.  
  75.         } else {
  76.  
  77.              variablesURL = "";
  78.  
  79.         }
  80.  
  81.        
  82.  
  83.        
  84.  
  85.              
  86.  
  87.              byte[] POSTbytes = variablesURL.getBytes();
  88.  
  89.              ByteArrayInputStream baos = new ByteArrayInputStream(POSTbytes);
  90.  
  91.              rQueue.queueRequest("http://www.zinsure.net/zinsure/JSONServlet", "POST", headers, myEvH, baos, POSTbytes.length, false);              
  92.  
  93.        
  94.  
  95.        
  96.  
  97.    }
  98.  
  99.  
  100.  
  101. private class MyEventHandler implements EventHandler {
  102.  
  103.         private static final int RANDOM_ID = 0x1337;
  104.  
  105.  
  106.  
  107.         private  String DEBUG_TAG = null;
  108.  
  109.        
  110.  
  111.         ByteArrayBuffer baf = new ByteArrayBuffer(20);
  112.  
  113.        
  114.  
  115.      
  116.  
  117.         private Activity myActivity;
  118.  
  119.      
  120.  
  121.         MyEventHandler(Activity activity) {
  122.  
  123.              this.myActivity = activity;  
  124.  
  125.              
  126.  
  127.         }
  128.  
  129.  
  130.  
  131.         public void data(byte[] bytes, int len) {
  132.  
  133.              baf.append(bytes, 0, len);  }
  134.  
  135.  
  136.  
  137.         public void endData() {
  138.  
  139.              String text = new String(baf.toByteArray());
  140.  
  141.              myShowNotificationAndLog("Data loaded: \n" + text);
  142.  
  143.          
  144.  
  145.                                        
  146.  
  147.                         } catch (JSONException e) {
  148.  
  149.                                 // TODO Auto-generated catch block
  150.  
  151.                                 e.printStackTrace();
  152.  
  153.                         }
  154.  
  155.              
  156.  
  157.  
  158.  
  159.              
  160.  
  161.            
  162.  
  163.         }
  164.  
  165.  
  166.  
  167.    
  168.  
  169.        
  170.  
  171.         public void status(int arg0, int arg1, int arg2, String s) {
  172.  
  173.              myShowNotificationAndLog("status [" + s + "]");  }
  174.  
  175.  
  176.  
  177.         public void error(int i, String s) {
  178.  
  179.              this.myShowNotificationAndLog("error [" + s + "]");  }
  180.  
  181.  
  182.  
  183.         public void handleSslErrorRequest(int arg0, String arg1, SslCertificate arg2) { }
  184.  
  185.         public void headers(Iterator arg0) { }
  186.  
  187.         public void headers(Headers arg0) { }
  188.  
  189.  
  190.  
  191.         private void myShowNotificationAndLog(String msg) {
  192.  
  193.            
  194.  
  195.              Log.d(DEBUG_TAG, msg);
  196.  
  197.        }
  198.  
  199.  
  200.  
  201.                 public void certificate(SslCertificate arg0) {
  202.  
  203.                         // TODO Auto-generated method stub
  204.  
  205.                        
  206.  
  207.                 }
  208.  
  209.  
  210.  
  211.                 public void handleSslErrorRequest(SslError arg0) {
  212.  
  213.                         // TODO Auto-generated method stub
  214.  
  215.                        
  216.  
  217.                 }
  218.  
  219.     }
Parsed in 0.046 seconds, using GeSHi 1.0.8.4
Nemat
Experienced Developer
Experienced Developer
 
Posts: 62
Joined: Thu Aug 21, 2008 3:16 pm
Location: Jaipur

Postby ninor » Mon Sep 29, 2008 11:58 am

I made a new app with your code, but I can't find RequestQueue.
android.net.http.RequestQueue
What imports are you using in this activity/service?

You said you were with SDK 1.0, wasn't it? Maybe your preferences aren't correctly mapped to the 1.0 directory.
Have you checked the directory specified in Eclipse -> Window -> Preferences -> Android?
User avatar
ninor
Moderator
Moderator
 
Posts: 180
Joined: Thu Aug 14, 2008 6:30 pm
Location: Barcelona, Spain

Postby ninor » Mon Sep 29, 2008 12:26 pm

Apart from these checks, you can see this example:

An example that demonstrates how HttpClient APIs can be used to perform form-based logon.

http://svn.apache.org/repos/asf/httpcom ... Login.java
User avatar
ninor
Moderator
Moderator
 
Posts: 180
Joined: Thu Aug 14, 2008 6:30 pm
Location: Barcelona, Spain

Postby Nemat » Mon Sep 29, 2008 1:34 pm

Thanks for your reply....
This code is working well in SDK-0.9 .I have to convert it into SDK-1.0.But I got errors in request queue and eventHandler class because these classes are removed from new SDK.I dont know which new classes are added instead of them.
Please give me any example of Http post for SDK-1.0.....

Thanks in Advance
Nemat
Experienced Developer
Experienced Developer
 
Posts: 62
Joined: Thu Aug 21, 2008 3:16 pm
Location: Jaipur

Top

Postby ninor » Mon Sep 29, 2008 3:49 pm

Here it is, directly ripped from the example I posted earlier.
The test page is simpler (thanks www.PragProg.com) with only an email and a password fields.
Also, I commented the code a bit, to set it clear.
Now, this must go inside a Thread to be really useful. You'll note some delay between starting the activity and showing the text. This is probably due to https connection setup.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.testing.httpPostTest;
  2.  
  3.  
  4.  
  5. import android.app.Activity;
  6.  
  7. import android.os.Bundle;
  8.  
  9. import android.util.Log;
  10.  
  11. import android.widget.TextView;
  12.  
  13. import java.io.IOException;
  14.  
  15. import java.util.ArrayList;
  16.  
  17. import java.util.List;
  18.  
  19. import org.apache.http.HttpEntity;
  20.  
  21. import org.apache.http.HttpResponse;
  22.  
  23. import org.apache.http.NameValuePair;
  24.  
  25. import org.apache.http.client.ClientProtocolException;
  26.  
  27. import org.apache.http.client.entity.UrlEncodedFormEntity;
  28.  
  29. import org.apache.http.client.methods.HttpGet;
  30.  
  31. import org.apache.http.client.methods.HttpPost;
  32.  
  33. import org.apache.http.cookie.Cookie;
  34.  
  35. import org.apache.http.impl.client.DefaultHttpClient;
  36.  
  37. import org.apache.http.message.BasicNameValuePair;
  38.  
  39. import org.apache.http.protocol.HTTP;
  40.  
  41.  
  42.  
  43. public class httpPostTest extends Activity {
  44.  
  45.  
  46.  
  47.         TextView textMsg;        
  48.  
  49.          
  50.  
  51.           /** Called with the activity is first created. */
  52.  
  53.           @Override
  54.  
  55.           public void onCreate(Bundle icicle) {
  56.  
  57.             super.onCreate(icicle);
  58.  
  59.            
  60.  
  61.             setContentView(R.layout.httplayout);
  62.  
  63.            
  64.  
  65.             // Associate component with layout
  66.  
  67.             textMsg=(TextView)findViewById(R.id.httptext);
  68.  
  69.            
  70.  
  71.             DefaultHttpClient httpclient = new DefaultHttpClient();    
  72.  
  73.                
  74.  
  75.             // Get cookies from the login page (not the address same of the form post)
  76.  
  77.                 HttpGet httpget = new HttpGet("https://secure.pragprog.com/login");
  78.  
  79.                
  80.  
  81.                 HttpResponse response;
  82.  
  83.                 try {
  84.  
  85.                         response = httpclient.execute(httpget);
  86.  
  87.                     HttpEntity entity = response.getEntity();
  88.  
  89.                    
  90.  
  91.                         Log.d("httpPost", "Login form get: " + response.getStatusLine());
  92.  
  93.                         if (entity != null) {
  94.  
  95.                             entity.consumeContent();
  96.  
  97.                         }
  98.  
  99.                        
  100.  
  101.                         Log.d("httpPost", "Initial set of cookies:");
  102.  
  103.                         List<Cookie> cookies = httpclient.getCookieStore().getCookies();
  104.  
  105.                         if (cookies.isEmpty()) {
  106.  
  107.                                 Log.d("httpPost", "None");
  108.  
  109.                         } else {
  110.  
  111.                             for (int i = 0; i < cookies.size(); i++) {
  112.  
  113.                                 Log.d("httpPost", "- " + cookies.get(i).toString());
  114.  
  115.                             }
  116.  
  117.                         }
  118.  
  119.  
  120.  
  121.                         // Preparing the post operation (address obtained from the Login page source; it's the form-action)
  122.  
  123.                         HttpPost httpost = new HttpPost("https://secure.pragprog.com/session?");
  124.  
  125.                        
  126.  
  127.                         List <NameValuePair> nvps = new ArrayList <NameValuePair>();
  128.  
  129.                         nvps.add(new BasicNameValuePair("email", "youremail@email.org"));
  130.  
  131.                         nvps.add(new BasicNameValuePair("password", "somepassword"));
  132.  
  133.                        
  134.  
  135.                         httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
  136.  
  137.                        
  138.  
  139.                         // Post, check and show the result (not really spectacular, but works):
  140.  
  141.                         response = httpclient.execute(httpost);
  142.  
  143.                         entity = response.getEntity();
  144.  
  145.                        
  146.  
  147.                         Log.d("httpPost", "Login form get: " + response.getStatusLine());
  148.  
  149.  
  150.  
  151.                         textMsg.setText("Response: " + response.getStatusLine());
  152.  
  153.                        
  154.  
  155.                         if (entity != null) {
  156.  
  157.                             entity.consumeContent();
  158.  
  159.                         }
  160.  
  161.                        
  162.  
  163.                         // Send the cookies grabbed from the login form
  164.  
  165.                         Log.d("httpPost", "Post logon cookies:");
  166.  
  167.                         cookies = httpclient.getCookieStore().getCookies();
  168.  
  169.                         if (cookies.isEmpty()) {
  170.  
  171.                                 Log.d("httpPost", "None");
  172.  
  173.                         } else {
  174.  
  175.                             for (int i = 0; i < cookies.size(); i++) {
  176.  
  177.                                 Log.d("httpPost", "- " + cookies.get(i).toString());
  178.  
  179.                             }
  180.  
  181.                         }                
  182.  
  183.  
  184.  
  185.                 } catch (ClientProtocolException e) {
  186.  
  187.                         Log.e("httpPost", e.getMessage());
  188.  
  189.                         e.printStackTrace();
  190.  
  191.                 } catch (IOException e) {
  192.  
  193.                         Log.e("httpPost", e.getMessage());
  194.  
  195.                         e.printStackTrace();
  196.  
  197.                 } catch (Exception e) {
  198.  
  199.                         Log.e("httpPost", e.getMessage());
  200.  
  201.                         e.printStackTrace();
  202.  
  203.                 }
  204.  
  205.         }
  206.  
  207. }
  208.  
  209.  
Parsed in 0.047 seconds, using GeSHi 1.0.8.4



And the layout (it's really complex!) :P
Filename: httplayout.xml

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="utf-8"?>
  2.  
  3. <LinearLayout
  4.  
  5.  xmlns:android="http://schemas.android.com/apk/res/android"
  6.  
  7.  android:orientation="vertical"
  8.  
  9.  android:layout_width="wrap_content"
  10.  
  11.  android:layout_height="wrap_content"
  12.  
  13.  android:layout_gravity="center_vertical|center_horizontal">
  14.  
  15.  
  16.  
  17.   <TextView
  18.  
  19.    android:layout_width="wrap_content"
  20.  
  21.    android:layout_height="wrap_content"
  22.  
  23.    android:text="Hola nenk" android:id="@+id/httptext"/>
  24.  
  25.  
  26.  
  27. </LinearLayout>
Parsed in 0.002 seconds, using GeSHi 1.0.8.4


Hope this helps.

edit: Beautified the code with Syntax tags 8)
User avatar
ninor
Moderator
Moderator
 
Posts: 180
Joined: Thu Aug 14, 2008 6:30 pm
Location: Barcelona, Spain

Postby Nemat » Tue Sep 30, 2008 1:28 pm

Thanks ninor......

now my code is working well....

Thanks a lot....
Nemat
Experienced Developer
Experienced Developer
 
Posts: 62
Joined: Thu Aug 21, 2008 3:16 pm
Location: Jaipur

Postby ElBerto » Wed Oct 01, 2008 2:47 am

ninor,
I am having trouble implementing the example you posted above. When I change the address to google, I get a failure message. I just changed the urls to 'https://www.google.com' which should work fine, but I get a 'The target server failed to respond' error message. Any thoughts?

Thanks
ElBerto
Freshman
Freshman
 
Posts: 2
Joined: Wed Oct 01, 2008 2:41 am

Postby ninor » Wed Oct 01, 2008 8:01 am

What login/service do you want to enter in?
Maybe there's no necessity for the HTTPS, so you can use HTTP.
User avatar
ninor
Moderator
Moderator
 
Posts: 180
Joined: Thu Aug 14, 2008 6:30 pm
Location: Barcelona, Spain

Postby ElBerto » Wed Oct 01, 2008 2:36 pm

Ninor,
Thanks for the reply. About 2 hours after posting this I stumbled across something weird. I have setup the development environment in Ubuntu. When I execute the Android application from within Eclipse and it transfers the program over to the emulator, the HTTPClient to https://www.google.com will fail. But when I reboot the emulator and launch it manually (or cause the system to crash and reboot by killing one of the root processes), it works fine. That is will work until I need to recompile and transfer the application from Eclipse. I was watching the SSL communication in Wireshark and it seems to be failing during the handshaking. I wonder if the Eclipse Plug-in is corrupting the certificate for google in some way.

Anyway, I am going to setup a Windows Environment this weekend and see if I see the same issue.

Again, Thanks for your help.
ElBerto
Freshman
Freshman
 
Posts: 2
Joined: Wed Oct 01, 2008 2:41 am

Postby ninor » Wed Oct 01, 2008 4:30 pm

Well, it seems that the SDK 1.0r1 should still be called a BETA version... :?

·
User avatar
ninor
Moderator
Moderator
 
Posts: 180
Joined: Thu Aug 14, 2008 6:30 pm
Location: Barcelona, Spain

Postby phannguyen » Thu Oct 02, 2008 11:18 am

hi ninor,
i have edit your httpPostTest to call a webservice . When debug, i got error at
Code: Select all
response = httpclient.execute(httpget);

I use httpClient to call a webservice, it's right?
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. ....
  3.  
  4.  DefaultHttpClient httpclient = new DefaultHttpClient();
  5.  
  6.          
  7.  
  8.          // Get cookies from the login page (not the address same of the form post)
  9.  
  10.           HttpGet httpget = new HttpGet("http://webservice.asmx");//webservice address is availabel
  11.  
  12.          
  13.  
  14.           HttpResponse response;
  15.  
  16.           try {
  17.  
  18.                response = httpclient.execute(httpget);// throw exception at here
  19.  
  20.               HttpEntity entity = response.getEntity();
  21.  
  22. ....
  23.  
  24.  
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


How i can call webservice ?
Android sdk 1.0 have many lib relate http (org.apache.http,org.apache.http.client,...) so i can't understand how to use it and what it mean.
Can u show me step by step to call webservice on android?

thanks a lot.
PhanNguyen
phannguyen
Experienced Developer
Experienced Developer
 
Posts: 56
Joined: Thu Jul 17, 2008 7:37 am

Postby ninor » Thu Oct 02, 2008 12:12 pm

I'm not sure if this code will allow connecting to a web service.
But if the web service in question is very simple, then: Can you send me via Private Msg the address of the webservice to check it?
Image AndDev: Your Android Development Community / Tutorials | Here's my Basic ToolKit
User avatar
ninor
Moderator
Moderator
 
Posts: 180
Joined: Thu Aug 14, 2008 6:30 pm
Location: Barcelona, Spain

Postby phannguyen » Fri Oct 03, 2008 3:23 am

hi ninor,
This is webservice address http://webservices.iter.dk/calculator.asmx
I pick up it from http://www.anddev.org/viewtopic.php?p=8837
But i don't want to use ksoap2 library, because there are many classes i can't convert to SDK 1.0 as u know in http://www.anddev.org/plshelp_me_conver ... t3005.html
So is there a simpler way to call a webservice that only use android sdk not another lib?
thanks for help.
PhanNguyen
phannguyen
Experienced Developer
Experienced Developer
 
Posts: 56
Joined: Thu Jul 17, 2008 7:37 am

Top
Next

Return to Networking & Database Problems

Who is online

Users browsing this forum: No registered users and 4 guests