如何在不使用外部库的情况下向服务器发送请求

时间:2015-10-25 12:04:10

标签: android httprequest

我有一个关于与Android手机和网络服务进行通信的问题。在上一次,我使用apache lib与服务器进行通信。但是,在当前任务中,我只想向服务器发送请求,而我并不关心服务器的响应。我们可以有任何简单的方法(不使用任何外部lib(即apache))来完成我的任务吗?我正在使用Android studio和SDK 23。

此外,我们有没有办法检查我的手机是否成功将请求发送到服务器?

这是使用apache的最后一个代码

public static String getStringContent(String uri) throws Exception {
            try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(uri));
            HttpResponse response = client.execute(request);
            InputStream ips  = response.getEntity().getContent();
            BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));

            StringBuilder sb = new StringBuilder();
            String s;
            while(true )
            {
                s = buf.readLine();
                if(s==null || s.length()==0)
                    break;
                sb.append(s);    
            }
            buf.close();
            ips.close();
            return sb.toString();    
            } 
        finally {
                   // any cleanup code...
                }
}

因此,我的解决方案是

URL urlToRequest = null;
    HttpURLConnection urlConnection = null;
    try {
        urlToRequest = new URL("server_link");
        urlConnection = (HttpURLConnection) urlToRequest.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");
       // urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

    } catch (IOException e) {
        e.printStackTrace();
    }

但是,什么也没发生。我认为我在第二段代码中出错了

1 个答案:

答案 0 :(得分:1)

试试这段代码。它没有外部库downlaod full code

public static String getData(String uri) {

        BufferedReader reader = null;

        try {
            URL url = new URL(uri);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }

    }