点击获取/发布请求在android中的URL,但没有请求在服务器端收到

时间:2015-05-31 05:43:57

标签: android android-intent android-activity

我试图在链接上发出get / post请求 http://103.48.108.35:5005/dataitsno 但没有请求在我的服务器上ping 我在我的Android应用程序上使用以下代码。 我也想在后台请求中发送它(不妨碍当前进程)。

public  void  SendCont() throws UnsupportedEncodingException {
String Name="Raj";
        String OwnNo="85859657";
        String text="";
        String data = URLEncoder.encode("owndat","UTF-8")+"="+URLEncoder.encode(OwnNo, "UTF-8");
        data += "&" + URLEncoder.encode("cont", "UTF-8") + "=" + URLEncoder.encode(Name, "UTF-8");
        BufferedReader reader=null;
        try
        {

            URL url = new URL("http://103.48.108.35:5005/dataitsno?quer='"+OwnNo+"'");

            // Send POST data request

            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write( data );
            wr.flush();

            // Get the server response

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }


            text = sb.toString();
        }
        catch(Exception ex)
        {

        }
        finally
        {
            try
            {

                reader.close();
            }

            catch(Exception ex) {}
        }

        // Show response on activity
        //content.setText( text  );
    }

1 个答案:

答案 0 :(得分:2)

这可能有助于你,

Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {

                try {

                    URL url = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setReadTimeout(10000 /* milliseconds */);
                    conn.setConnectTimeout(15000 /* milliseconds */);
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);
                    // Starts the query

                    conn.connect();
                    InputStream stream = conn.getInputStream();

                    String data = convertStreamToString(stream);

                    // u can read data here
                    stream.close();


                } catch (Exception e) {
                }
            }
        });

        thread.start();

&安培; convertStreamToString是,

static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }