Skip to content

Instantly share code, notes, and snippets.

@aftabsikander
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save aftabsikander/533b0309d9ad5320266f to your computer and use it in GitHub Desktop.

Select an option

Save aftabsikander/533b0309d9ad5320266f to your computer and use it in GitHub Desktop.
Get Response from Webservice and converts into String
public static String getDataFromURL(URL url) throws IOException
{
OkHttpClient client = new OkHttpClient();
HttpURLConnection connection = client.open(url);
InputStream in = null;
try
{
// Read the response.
in = connection.getInputStream();
return convertStreamToString(in);
}
finally
{
if (in != null)
in.close();
}
}
public static String sendDataToServer(URL url) throws IOException
{
OkHttpClient client = new OkHttpClient();
HttpURLConnection connection = client.open(url);
OutputStream out = null;
InputStream in = null;
try
{
// Write the request.
connection.setRequestMethod("POST");
out = connection.getOutputStream();
out.close();
// Read the response.
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new IOException("Unexpected HTTP response: " + connection.getResponseCode() + " " + connection.getResponseMessage());
}
in = connection.getInputStream();
return convertStreamToString(in);
}
finally
{
// Clean up.
if (out != null)
out.close();
if (in != null)
in.close();
}
}
private static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment