Web服务在浏览器上工作正常,但不是从Android代码

时间:2013-06-05 08:35:21

标签: android web-services

我正在尝试为我的应用程序创建登录。当我在Web浏览器中尝试它时给定的URL工作正常,但Web服务不能使用Android应用程序中的以下代码。出于测试目的,我对网址链接进行了硬编码。 我已在manifest.xml文件中设置了internet权限。

String uri= "http://192.168.1.6:8080/Cloud/webresources/generic/login?user=ankita&pass=1234";
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(uri);
    HttpResponse response = httpclient.execute(httpget);
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK)
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        String responseString = out.toString();
        if(responseString.equals("success"))
        {
            System.out.println("Successful login");
            Intent intent = new Intent(this, DisplayDetailsActivity.class);
            String message = "User id is: success";//+userid.toString();
            intent.putExtra(EXTRA_MESSAGE, message);
            startActivity(intent);
        }
        else
        {
            System.out.println("Unsuccessful login");
        }
    }

任何帮助将不胜感激。感谢。

3 个答案:

答案 0 :(得分:0)

您可以尝试以下代码

 try {
        DefaultHttpClient client = new DefaultHttpClient();

        String uri= "http://192.168.1.6:8080/Cloud/webresources/generic/login?"

        String request = uri + java.net.URLEncoder.encode("user=ankita&pass=1234", "UTF-8");

        HttpGet get = new HttpGet(request);
        HttpResponse responseGet = client.execute(get);
        HttpEntity resEntityGet = responseGet.getEntity();

        if (resEntityGet != null) {
            String response = EntityUtils.toString(resEntityGet);
            Log.i("Search Response", response);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

你是否在清单中写了这两行

<uses-permission android:name="android.permission.INTERNET" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
    </uses-permission>

答案 1 :(得分:0)

您可以尝试使用此代码。

 HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://192.168.1.6:8080/Cloud/webresources/generic/login");
    try {
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
      nameValuePairs.add(new BasicNameValuePair("user","ankita"));
       nameValuePairs.add(new BasicNameValuePair("pass","1234"));
      post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      HttpResponse response = client.execute(post);
      BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      String line = "";
      while ((line = rd.readLine()) != null) {
        System.out.println(line);
      }

    } catch (IOException e) {
      e.printStackTrace();
    }

AndroidManifest.xml 文件中添加适当的权限。

答案 2 :(得分:0)

@Ankita您是否在AsyncTask Thread中添加了代码?