使用Android提出HTTP请求
-
29-09-2019 - |
题
我到处搜索,但找不到答案,有没有办法提出简单的HTTP请求?我想在我的网站之一上请求PHP页面 /脚本,但我不想显示网页。
如果可能的话,我什至想在后台(在广播中)这样做
解决方案
更新
这是一个非常古老的答案。我绝对不会再推荐Apache的客户。而是使用两者:
原始答案
首先,请求访问网络的权限,在您的清单中添加以下内容:
<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());
}
如果您希望它在单独的线程上运行,我建议扩展异步:
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");
其他提示
除非您有明确的理由选择apache HTTPClient,否则您应该更喜欢Java.net.urlConnection。您可以找到有关如何在网络上使用它的示例。
自您原始帖子以来,我们还改进了Android文档: http://developer.android.com/reference/java/net/httpurlconnection.html
我们已经在官方博客上谈论了权衡: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
注意:Apache HTTP客户端与Android捆绑在一起 httpurlconnection. 。请参阅Android开发人员 博客 更多细节。
添加 <uses-permission android:name="android.permission.INTERNET" />
表现出来。
然后,您会检索一个网页:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}
finally {
urlConnection.disconnect();
}
我还建议在单独的线程上运行它:
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
String responseString = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if(conn.getResponseCode() == HttpsURLConnection.HTTP_OK){
// Do normal input or output stream reading
}
else {
response = "FAILED"; // See documentation for more info on response handling
}
} 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..
}
}
看到 文档 有关响应处理和发布请求的更多信息。
最简单的方法是使用称为Android Lib 凌空
射击提供以下好处:
网络请求的自动调度。 多个并发网络连接. 。具有标准HTTP缓存相干性的透明磁盘和内存响应缓存。支持请求优先级。取消请求API。您可以取消单个请求,也可以设置请求的块或范围取消。易于自定义,例如重试和退缩。强大的订购使您可以轻松地使用网络异步获取的数据正确填充UI。调试和跟踪工具。
您可以简单地发送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);
在这种情况下,您无需考虑自己“在后台运行”或“使用缓存”自己,因为所有这些都已经由Alley完成。
private String getToServer(String service) throws IOException {
HttpGet httpget = new HttpGet(service);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return new DefaultHttpClient().execute(httpget, responseHandler);
}
问候
查看这个可通过gradle获得的很棒的新图书馆:)
build.gradle: compile 'com.apptakk.http_request:http-request:0.1.2'
用法:
new HttpRequestTask(
new HttpRequest("http://httpbin.org/post", HttpRequest.POST, "{ \"some\": \"data\" }"),
new HttpRequest.Handler() {
@Override
public void response(HttpResponse response) {
if (response.code == 200) {
Log.d(this.getClass().toString(), "Request successful!");
} else {
Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
}
}
}).execute();
与线程:
private class LoadingThread extends Thread {
Handler handler;
LoadingThread(Handler h) {
handler = h;
}
@Override
public void run() {
Message m = handler.obtainMessage();
try {
BufferedReader in =
new BufferedReader(new InputStreamReader(url.openStream()));
String page = "";
String inLine;
while ((inLine = in.readLine()) != null) {
page += inLine;
}
in.close();
Bundle b = new Bundle();
b.putString("result", page);
m.setData(b);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler.sendMessage(m);
}
}
我使用gson lib来为网站服务的网站服务来源:
客户:
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
在 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
}
对我来说,最简单的方法是使用库 retrofit2
我们只需要创建一个包含我们的请求方法,参数的界面,也可以为每个请求制作自定义标题:
public interface MyService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
@GET("user")
Call<UserDetails> getUserDetails(@Header("Authorization") String credentials);
@POST("users/new")
Call<User> createUser(@Body User user);
@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first,
@Field("last_name") String last);
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo,
@Part("description") RequestBody description);
@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);
}
最好的是,我们可以使用入伍方法轻松地做到这一点
因为没有一个答案描述了一种执行请求的方法 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();
该库的明确优势在于,它从一些低级细节中抽象出我们,提供了更友好和安全的方式与它们互动。该语法也被简化,并允许编写不错的代码。
如上所述使用齐射。添加到build.gradle(模块:应用程序)中
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客户端,非常简单。