简体   繁体   中英

How can you send a web request from inside an Android app?

Please excuse my lack of knowledge on the topic, but I have very little, if any knowledge of networking, PHP, web requests, and such. Essentially, I want to send a string to a website for logging using $_GET variables. How can I send a string using this method, from inside the app?

(I can't self answer for another 6 hours, but if I COULD, here is what it would look like, with the code in the answer of course. Just didn't wan't to take away from the original question.)

In the end, the code found here worked. The app sends a request to the web server, which then appends the string in the $_GET variable to a log file! Took a few hours to figure out though. :l

You can use the Apache Commons HttpClient library to make HTTP requests.

HTTP request URIs consist of a protocol scheme, host name, optional port, resource path, optional query, and optional fragment.

HttpGet httpget = new HttpGet(
     "http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq=");

Query string can also be generated from individual parameters:

List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("q", "httpclient"));
qparams.add(new BasicNameValuePair("btnG", "Google Search"));
qparams.add(new BasicNameValuePair("aq", "f"));
qparams.add(new BasicNameValuePair("oq", null));
URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search", 
    URLEncodedUtils.format(qparams, "UTF-8"), null);
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());

wanstein is right, but the URIUtils.createURI is deprecated now (4.2.1), so it is better to use the URIBuilder:

URI uri = new URIBuilder()
                .setFragment("http")
                .setHost(HOST)
                .setPath(path)
                .setQuery(URLEncodedUtils.format(qparams, "UTF-8"))
                .build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM