Skip to content

Instantly share code, notes, and snippets.

@nacho4d
Created February 22, 2017 03:06
Show Gist options
  • Save nacho4d/0997f4acc8b52d0846f84b9ab350dfe8 to your computer and use it in GitHub Desktop.
Save nacho4d/0997f4acc8b52d0846f84b9ab350dfe8 to your computer and use it in GitHub Desktop.
Read body of HttpURLConnection as String
package com.ibm.sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Sample {
public void getSomeUrl(String sessionUrl, String method) throws IOException {
URL uri = new URL(sessionUrl);
HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("content-type", "application/x-www-form-url-encoded");
//connection.setDoOutput(true);
connection.connect();
StringBuffer body = new StringBuffer();
int httpStatus = getConnectionResponse(connection, body);
System.out.println("Response:");
System.out.println(" httpStatus: '" + httpStatus + "'");
System.out.println(" headers: '" + connection.getHeaderFields().toString() + "'");
System.out.println(" body: '" + body.toString() + "'");
}
public int getConnectionResponse(HttpURLConnection connection, StringBuffer bodyOut) throws IOException {
int httpStatus = connection.getResponseCode();
if (bodyOut != null && connection.getInputStream() != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
bodyOut.append(inputLine);
}
in.close();
}
return httpStatus;
}
public static void main(String[] args) throws IOException {
Sample s = new Sample();
System.out.println("HEAD: ");
s.getSomeUrl("http://www.google.co.jp", "HEAD");
System.out.println("");
System.out.println("GET: ");
s.getSomeUrl("http://www.google.co.jp", "GET");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment