标准网络请求

时间:2013-04-17 19:18:02

标签: java android standards httpurlconnection

我想知道是否有某种通用的方式来使用Java / Android进行网络调用,因为我正在努力应对我目前的策略。我正在尝试这个:

public static File synchronousConnection(String url, String requestMethod, byte[] requestData, Map<String, String> headers)
{
    File returnData = null;
    try
    {
        URL url = new URL(url);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod(requestMethod);
        if(requestData != null && requestData.length > 0)connection.setRequestProperty("Content-Length", Integer.toString(requestData.length));
        if(headers != null)for(String key : headers.keySet())connection.setRequestProperty(key, headers.get(key));
        //connection.connect();

        if(requestData != null && requestData.length > 0)
        {
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(requestData);

            outputStream.flush();
            outputStream.close();
        }

        //String response = inputStreamToString(url.openStream());
        //System.out.println("Response: " + response);

        int statusCode = connection.getResponseCode();

        connection.disconnect();

        System.out.println("Status code: " + statusCode);

        //returnData = response;
    }
    catch(IOException e)
    {
        System.out.println("IO Exception in connections\n" + e.getLocalizedMessage());
        e.printStackTrace();
    }
    catch(Exception e)
    {
        System.out.println("Invalid information for network connection\n" + e.getLocalizedMessage());
        e.printStackTrace();
    }
    return returnData;
}

我有相当多的组件被注释掉了,因为它们似乎会干扰过程或提出问题,即使它们在其他示例中也是如此。至于inputStreamToString(InputStream),这是我做其所说内容的方法之一。

根据我对函数的输入参数,是否存在URL连接的通用方法?目前,我真的很难获得任何工作连接,而且很奇怪必须以自定义方式为每个请求做事。此外,我似乎无法从POST请求获得任何响应数据,即使我的API确实返回了响应正文。

0 个答案:

没有答案