I was wondering if there is some sort of generic way to make network calls with Java / Android, as I'm struggling with my current tactics. I'm currently trying this:
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;
}
I have a fair bit of components commented out, as they seemed to interfere with the process or bring up issues, even though they were in other examples. As for inputStreamToString(InputStream)
, that is one of my methods to do just what it says.
Is there a generic way to a URL connection, given my input parameters to the function? Currently, I'm really struggling to get any connections to work and its odd to have to do things in a custom way for each request. Also, I can't seem to get any response data back from a POST
request, even though my API does return a response body.