通过http android连接到安全服务器

时间:2013-06-03 07:49:20

标签: android androidhttpclient

我正在尝试连接以进行身份​​验证并连接到安全服务器,但它失败并向Throwable干杯。这是我的http连接代码

            // 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();
        }

更新:从chintan-khetiya回答我做了这个,但我收到了日志警告

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");
                }

记录警告:

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)

我替换了

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

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.

但警告错误仍然存​​在且仍无响应。

1 个答案:

答案 0 :(得分:2)

异常细节看起来很简单:java.net.UnknownHostException: URL似乎是错误的。你能在PC浏览器中打开网址吗?