I'm trying to do a http request in Java with the Apache Api (httpcomponents) on api.stackexchange. But this request returns text and not html.
Here is my code:
public class HttpRequestBrute {
public static void main(String[] args) throws Exception {
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("api.stackexchange.com").setPath("/2.0/search")
.setParameter("site", "stackoverflow")
.setParameter("intitle" ,"workaround")
.setParameter("tagged","javascript");
URI uri = builder.build();
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget1 = new HttpGet(uri);
System.out.println("executing request " + httpget1.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget1, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
System.out.println("----------------------------------------");
} finally {
httpclient.getConnectionManager().shutdown();
}
}
}
It's seems to have an error in the return json value at line 1 column 19.
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 19
The response you are getting (after hitting http://api.stackexchange.com/2.0/search?site=stackoverflow&intitle=workaround&tagged=javascript)
Its not a simple text. Its a JSON response. You will need a Java JSON parser like google-gjson to parse this.