import java.io.BufferedReader; import java.net.HttpURLConnection; import java.net.URL;
import java.io.InputStreamReader;  import java.io.OutputStreamWriter;
public class SparqlEncPOST {
  public static void main(String[] args) { try {  BufferedReader br = null;
    URL inputURL = new URL("http://dbpedia.org/sparql");
    String q="query=construct+{+?X+a+<foo:country>}" +
             "+where+{?X+a+<http://dbpedia.org/ontology/Country>}";
    HttpURLConnection con = (HttpURLConnection) inputURL.openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(true);
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("Accept", "text/turtle");
    con.connect();
      OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
      wr.write(q); wr.flush(); wr.close();
    String s = "";   StringBuffer res= new StringBuffer();
    br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
    while ((s = br.readLine()) != null) { res.append(s+ "\n");	}
    br.close();  System.out.println(res);  // or fill XML from Reader
  } catch (Exception e) { e.printStackTrace(); } }}
