我想知道是否有某种通用方法可以使用 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 确实返回了响应正文,我似乎也无法从请求中获取任何响应数据。