使用android发出HTTP请求

使用android发出HTTP请求,android,httpwebrequest,androidhttpclient,Android,Httpwebrequest,Androidhttpclient,我到处都搜索了,但是我找不到我的答案,有没有办法发出一个简单的HTTP请求?我想在我的一个网站上请求一个PHP页面/脚本,但我不想显示该网页 如果可能的话,我甚至想在后台(在广播接收器中)用一个线程执行此操作: private class LoadingThread extends Thread { Handler handler; LoadingThread(Handler h) { handler = h; } @Override p

我到处都搜索了,但是我找不到我的答案,有没有办法发出一个简单的HTTP请求?我想在我的一个网站上请求一个PHP页面/脚本,但我不想显示该网页

如果可能的话,我甚至想在后台(在广播接收器中)用一个线程执行此操作:

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);
    }
}
更新 这是一个非常古老的答案。我绝对不会再推荐Apache的客户端了。相反,请使用以下任一选项:

原始答案 首先,请求访问网络的权限,将以下内容添加到您的清单中:

<uses-permission android:name="android.permission.INTERNET" />
如果希望它在单独的线程上运行,我建议扩展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..
    }
}

除非您有明确的理由选择Apache HttpClient,否则您应该更喜欢java.net.URLConnection。你可以在网上找到很多关于如何使用它的例子

我们还改进了Android文档,因为您的原始帖子:


我们在官方博客上讨论了取舍问题:

我使用Gson库为一个Web服务重新查询URL做了这个:

客户:

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;
}
私有字符串getToServer(字符串服务)引发IOException{
HttpGet HttpGet=新的HttpGet(服务);
ResponseHandler ResponseHandler=新BasicResponseHandler();
返回新的DefaultHttpClient().execute(httpget,responseHandler);
}

关于

注意:与Android捆绑在一起的Apache HTTP客户端现在被弃用,取而代之的是。有关更多详细信息,请参见Android开发者

添加到您的清单中

然后,您将检索如下所示的网页:

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..
}
}
class RequestTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字符串…uri){
字符串responseString=null;
试一试{
URL=新URL(myurl);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
if(conn.getResponseCode()==HttpsURLConnection.HTTP\u确定){
//进行正常的输入或输出流读取
}
否则{
response=“FAILED”;//有关响应处理的详细信息,请参阅文档
}
}捕获(客户端协议例外e){
//处理问题。。
}捕获(IOE异常){
//处理问题。。
}
回报率;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
//做任何有反应的事。。
}
}

有关响应处理和POST请求的更多信息,请参阅。这是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
 }

看看这个很棒的新图书馆,可通过gradle获得:)

build.gradle:
编译'com.apptakk.http\u请求:http请求: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();

对我来说,最简单的方法是使用名为

我们只需要创建一个包含请求方法、参数的接口,还可以为每个请求创建自定义头:

    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);    

    }
公共接口MyService{
@获取(“用户/{user}/repos”)
调用listRepos(@Path(“user”)字符串user);
@获取(“用户”)
调用getUserDetails(@Header(“Authorization”)字符串凭据);
@帖子(“用户/新”)
调用createUser(@Body User);
@FormUrlEncoded
@发布(“用户/编辑”)
首先调用updateUser(@Field(“first_name”)字符串,
@字段(“姓氏”)字符串(最后一个);
@多部分
@放置(“用户/照片”)
调用updateUser(@Part(“photo”)RequestBody photo,
@部分(“说明”)请求主体说明);
@标题({
“接受:application/vnd.github.v3.full+json”,
“用户代理:改装示例应用程序”
})
@获取(“用户/{username}”)
调用getUser(@Path(“username”)字符串username);
}

最好的方法是,我们可以使用排队方法轻松地异步完成这项工作。最简单的方法是使用名为

截击有以下好处:

网络请求的自动调度多并发网络 连接。透明的磁盘和内存响应缓存 标准HTTP缓存一致性。支持请求优先级划分。 取消请求API。您可以取消单个请求,也可以 设置要取消的请求块或范围。易于定制,例如 例如,用于重试和退避。强大的排序功能,易于 使用从用户界面异步获取的数据正确填充用户界面 网络。调试和跟踪工具

您可以发送如下简单的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);
//实例化RequestQueue。
RequestQueue=Volley.newRequestQueue(this);
字符串url=”http://www.yourapi.com";
JsonObjectRequest=新的JsonObjectRequest(url,null,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
if(null!=响应){
试一试{
//处理好你的反应
}捕获(JSONException e){
e、 printStackTrace();
}
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
}
});
添加(请求);

在这种情况下,您不必考虑“后台运行”或“使用缓存”,因为所有这些都已经通过截击完成了。

因为没有一个答案描述了用java来执行请求的方式,这是当今Android和Java中非常流行的HTTP客户端。
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();
    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);    

    }
        // 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);
//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();
implementation 'com.android.volley:volley:1.1.1'
<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);
}