简体   繁体   English

如何从Android应用程序内部发送网络请求?

[英]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. 请原谅我缺乏关于该主题的知识,但是我对网络,PHP,Web请求等的了解很少。 Essentially, I want to send a string to a website for logging using $_GET variables. 本质上,我想使用$ _GET变量将字符串发送到网站进行日志记录。 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.) (我无法再自己回答6个小时,但是如果可以的话,这就是它的样子,当然还有答案中的代码。只是不想离开最初的问题。)

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! 该应用程序向Web服务器发送请求,然后Web服务器将$ _GET变量中的字符串附加到日志文件! Took a few hours to figure out though. 花了几个小时才弄清楚。 :l :L

You can use the Apache Commons HttpClient library to make HTTP requests. 您可以使用Apache Commons HttpClient库发出HTTP请求。

HTTP request URIs consist of a protocol scheme, host name, optional port, resource path, optional query, and optional fragment. HTTP请求URI由协议方案,主机名,可选端口,资源路径,可选查询和可选片段组成。

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: wanstein是正确的,但是现在不推荐使用URIUtils.createURI (4.2.1),因此最好使用URIBuilder:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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