我到处都找过了,但我找不到我的答案,有没有一种方法可以做一个简单的HTTP请求?我想在我的一个网站上请求一个PHP页面/脚本,但我不想显示网页。
如果可能的话,我甚至想在后台(在一个BroadcastReceiver)做它
我到处都找过了,但我找不到我的答案,有没有一种方法可以做一个简单的HTTP请求?我想在我的一个网站上请求一个PHP页面/脚本,但我不想显示网页。
如果可能的话,我甚至想在后台(在一个BroadcastReceiver)做它
当前回答
按照上面的建议使用凌空射击。添加以下到构建。gradle(模块:app)
implementation 'com.android.volley:volley:1.1.1'
在AndroidManifest.xml中添加以下内容:
<uses-permission android:name="android.permission.INTERNET" />
并添加以下活动代码:
public void httpCall(String url) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// enjoy your response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// enjoy your error status
}
});
queue.add(stringRequest);
}
它取代了http客户端,非常简单。
其他回答
最简单的方法是使用名为Volley的Android库
Volley offers the following benefits: Automatic scheduling of network requests. Multiple concurrent network connections. Transparent disk and memory response caching with standard HTTP cache coherence. Support for request prioritization. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel. Ease of customization, for example, for retry and backoff. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network. Debugging and tracing tools.
你可以发送一个http/https请求,简单如下:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.yourapi.com";
JsonObjectRequest request = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (null != response) {
try {
//handle your response
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
在这种情况下,你不必考虑“运行在后台”或“使用缓存”自己,因为所有这些都已经完成了Volley。
更新
这是一个非常古老的答案。我绝对不会再推荐Apache的客户端了。你可以用任意一种:
改造 OkHttp 截击 HttpUrlConnection
原来的答案
首先,申请访问网络的权限,在您的清单中添加以下内容:
<uses-permission android:name="android.permission.INTERNET" />
那么最简单的方法是使用Apache http客户端与Android捆绑:
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
out.close();
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
如果你想让它在单独的线程上运行,我建议扩展AsyncTask:
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
然后,你可以通过以下方式提出请求:
new RequestTask().execute("http://stackoverflow.com");
由于没有一个回答描述了一种使用OkHttp执行请求的方法,这是目前在Android和Java上非常流行的http客户端,我将提供一个简单的例子:
//get an instance of the client
OkHttpClient client = new OkHttpClient();
//add parameters
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://www.example.com").newBuilder();
urlBuilder.addQueryParameter("query", "stack-overflow");
String url = urlBuilder.build().toString();
//build the request
Request request = new Request.Builder().url(url).build();
//execute
Response response = client.newCall(request).execute();
这个库的明显优势是,它将我们从一些低级细节中抽象出来,提供了更友好和安全的方式与它们交互。语法也被简化,允许编写漂亮的代码。
我做了这个webservice请求URL,使用一个Gson库:
客户:
public EstabelecimentoList getListaEstabelecimentoPorPromocao(){
EstabelecimentoList estabelecimentoList = new EstabelecimentoList();
try{
URL url = new URL("http://" + Conexao.getSERVIDOR()+ "/cardapio.online/rest/recursos/busca_estabelecimento_promocao_android");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != 200) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
estabelecimentoList = new Gson().fromJson(br, EstabelecimentoList.class);
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return estabelecimentoList;
}
这是android中HTTP Get/POST请求的新代码。HTTPClient已被废弃,可能无法使用,因为在我的情况下。
首先在build.gradle中添加两个依赖:
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
然后在ASyncTask in doBackground方法中编写此代码。
URL url = new URL("http://localhost:8080/web/get?key=value");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
InputStream it = new BufferedInputStream(urlConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
StringBuilder dta = new StringBuilder();
String chunks ;
while((chunks = buff.readLine()) != null)
{
dta.append(chunks);
}
}
else
{
//Handle else
}