3

I am trying to connect to authenticate and connect to a secure server but it fails and toast to Throwable t. Here is my http connection code

            // Log.i(getClass().getSimpleName(), "send  task - start");
            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams,
                    15000);
            HttpConnectionParams.setSoTimeout(httpParams, 15000);
            //
            HttpParams p = new BasicHttpParams();
            // p.setParameter("name", pvo.getName());
            p.setParameter("user", "1");

            // Instantiate an HttpClient
            HttpClient httpclient = new DefaultHttpClient(p);
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(":jeunes-caisse-depargne", "HREwFdin3r6Y"); 
            ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), credentials);

            String url = "http://www.1.json";
            HttpPost httppost = new HttpPost(url);

            // Instantiate a GET HTTP method
            try {
                Log.i(getClass().getSimpleName(), "send  task - start");
                //
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                        2);
                nameValuePairs.add(new BasicNameValuePair("user", "1"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String responseBody = httpclient.execute(httppost,
                        responseHandler);
                // Parse
                JSONObject json = new JSONObject(responseBody);
                JSONArray jArray = json.getJSONArray("posts");
                ArrayList<HashMap<String, String>> mylist = 
                       new ArrayList<HashMap<String, String>>();

                for (int i = 0; i < jArray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    JSONObject e = jArray.getJSONObject(i);
                    String s = e.getString("post");
                    JSONObject jObject = new JSONObject(s);


                    map.put("UserName", jObject.getString("xxxxx"));
                    map.put("FullName", jObject.getString("xxxxxx"));

                    mylist.add(map);
                }
                Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // Log.i(getClass().getSimpleName(), "send  task - end");

         catch (Throwable t) {
            Toast.makeText(this, "Request failed: " + t.toString(),
                    Toast.LENGTH_LONG).show();
        }

UPDATE : From chintan-khetiya answer i did this but i got a log warning

HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;
                JSONObject json = new JSONObject();

                try {
                HttpPost post = new HttpPost("depargne.fr....");
                json.put("user_name", "xxxx");
                json.put("password", "xxx");
                StringEntity se = new StringEntity( json.toString());  
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);

                 /*Checking response */
                if(response!=null){
                is = response.getEntity().getContent(); //Get the data in the entity
                 }


                try 
                {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) 
                    {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();
                    System.out.println("Result: "+result);
                }
                catch (Exception e) 
                {   
                    Log.e("Loading Runnable Error converting result :", e.toString());
                }


                } catch(Exception e) {
                e.printStackTrace();
                //createDialog("Error", "Cannot Estabilish Connection");
                }

Log warning :

06-03 12:05:38.703: W/System.err(13696): java.net.UnknownHostException: .fr
06-03 12:05:38.703: W/System.err(13696):    at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
06-03 12:05:38.703: W/System.err(13696):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
06-03 12:05:38.707: W/System.err(13696):    at java.net.InetAddress.getAllByName(InetAddress.java:256)
06-03 12:05:38.707: W/System.err(13696):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
06-03 12:05:38.707: W/System.err(13696):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-03 12:05:38.707: W/System.err(13696):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-03 12:05:38.707: W/System.err(13696):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
06-03 12:05:38.707: W/System.err(13696):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-03 12:05:38.707: W/System.err(13696):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-03 12:05:38.707: W/System.err(13696):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
06-03 12:05:38.707: W/System.err(13696):    at tionce.app.MainActivity.onClick(MainActivity.java:122)
06-03 12:05:38.707: W/System.err(13696):    at android.view.View.performClick(View.java:2538)
06-03 12:05:38.707: W/System.err(13696):    at android.view.View$PerformClick.run(View.java:9152)
06-03 12:05:38.707: W/System.err(13696):    at android.os.Handler.handleCallback(Handler.java:587)
06-03 12:05:38.707: W/System.err(13696):    at android.os.Handler.dispatchMessage(Handler.java:92)
06-03 12:05:38.707: W/System.err(13696):    at android.os.Looper.loop(Looper.java:130)
06-03 12:05:38.707: W/System.err(13696):    at android.app.ActivityThread.main(ActivityThread.java:3687)
06-03 12:05:38.707: W/System.err(13696):    at java.lang.reflect.Method.invokeNative(Native Method)
06-03 12:05:38.707: W/System.err(13696):    at java.lang.reflect.Method.invoke(Method.java:507)
06-03 12:05:38.707: W/System.err(13696):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
06-03 12:05:38.710: W/System.err(13696):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
06-03 12:05:38.710: W/System.err(13696):    at dalvik.system.NativeStart.main(Native Method)

I replaced

  HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams,
                    15000);
            HttpConnectionParams.setSoTimeout(httpParams, 15000);

with

DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1"));
        client.addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                AuthState state = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                if (state.getAuthScheme() == null) {
                    BasicScheme scheme = new BasicScheme();
                    CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
                    org.apache.http.auth.Credentials credentials = credentialsProvider.getCredentials(AuthScope.ANY);
                    if (credentials == null) {
                        throw new HttpException();
                    }
                    state.setAuthScope(AuthScope.ANY);
                    state.setAuthScheme(scheme);
                    state.setCredentials(credentials);
                }
            }
        }, 0); // 0 = first, and you really want to be first.

but the warning error still occur and still no response.

Dimitri
  • 677
  • 3
  • 19
  • 46
  • Can you share exception details? – gunar Jun 03 '13 at 07:52
  • check out [Here](http://stackoverflow.com/questions/13134019/http-post-method-passing-null-values-to-the-server/13134287#13134287) & [Here](http://chintankhetiya.wordpress.com/) – Chintan Khetiya Jun 03 '13 at 07:52
  • chintankhetiya please look at my update after applying your solution and @gunar. check the updated sample i got a warning but no response – Dimitri Jun 03 '13 at 08:13

1 Answers1

2

Exception detail looks straight-forward: java.net.UnknownHostException: The URL seems to be wrong. Can you open the url in PC browser?

gunar
  • 14,660
  • 7
  • 56
  • 87
  • the url is good but can it be the username and password too ? – Dimitri Jun 03 '13 at 08:39
  • I just tried to open 'http://www.jeunes-caisse-depargne.fr/' in browser (Chrome) and I am getting a 404. Maybe the url is accessible to you because you're in an intranet, but the device is not? – gunar Jun 03 '13 at 08:42
  • Would this help? http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html – gunar Jun 03 '13 at 08:53
  • There must be a typo in the URL. It has nothing to do with credentials or parameters. Just the domain name. Be also sure that the domain name is resolvable by your test device (e.g. internal names might not be). Finally get rid of the ":" for the username. That could also be the reason. – Wolfram Rittmeyer Jun 04 '13 at 11:21