Android: Using HttpGet to send a URL

2019-06-12 19:41发布

问题:

I'm trying to send a URL to my server that uses values from edittext fields. Currently it continues to force close on the button click. This is what I have:

Button testbtn = (Button) findViewById(R.id.Testbtn);
testbtn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        HttpGet method = new HttpGet("http://mysite.com/test.php?first=<>&last=<>&address=<>&phone=<>&zip=<>&email=<>");
        HttpClient client = new DefaultHttpClient();
        try {
            client.execute(method);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
});

I haven't put the edittext values in the <> of the URL yet, but I assume that wouldn't cause any problems. Why won't it send the URL?

I don't want it to open a browser or anything like that but send the URL in the background and then I would have an intent that would return them to their previous screen.

回答1:

At the moment you are not sending anything.

HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/");

    try {
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        HttpEntity ht = response.getEntity();

            BufferedHttpEntity buf = new BufferedHttpEntity(ht);

            InputStream is = buf.getContent();

            BufferedReader r = new BufferedReader(new InputStreamReader(is));

            StringBuilder total = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null) {
                total.append(line);
            }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Hope this helps!

UPDATE

Change HttpPost to HttpGet both work ;)



回答2:

The client is null. You must initialize it.