在没有httpClient的情况下从android发送HTTP Get和Post请求

时间:2015-10-28 22:04:01

标签: android httprequest android-networking

我尝试从Android应用程序中使用Web服务休息,但是当我查找示例时,发现只有两种方法,httpClient已被弃用,我甚至无法为我的应用程序导入它的版本,而且,方法使用HttpURLConnection,它不会像预期的那样工作。

我的代码就在这一刻:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestConnect  {
    public static String listar() throws IOException {
       try {
           URL reqURL = new URL("http://localhost/wsRest/index.php/contact");
           HttpURLConnection request = (HttpURLConnection) (reqURL.openConnection());
           request.setRequestMethod("GET");
           request.connect();

        } catch (Exception e) {
            return "Nope!";
        }
        return "YESSSS!";
    }
}

如何访问我的网址并轻松获取内容,即Get和Post方法?

非常感谢大家!

2 个答案:

答案 0 :(得分:1)

更好地使用真棒http库https://github.com/square/okhttp

例如,请尝试以下代码段:

student = Student.find(1)
student.courses

另一个很棒的解决方案(也来自square小组)是Retrofit

答案 1 :(得分:1)

试试这个

 URL url = new URL(urlpath.toString()); // Your given URL.
     HttpURLConnection c = (HttpURLConnection) url.openConnection();
     c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new   InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }