[SOLVED] OctoPrint via Android app

I'm trying to write an Android app to access the OctoPrint API. My problem is that I always get a HTML request - not JSON.

My code

Uri.Builder builder = new Uri.Builder( );
builder.scheme( "http" );
builder.encodedAuthority( "172.16.0.150:5000" );
builder.appendQueryParameter( "/api/version", "" );
builder.appendQueryParameter( "HTTP/1.1", "" );
builder.appendQueryParameter( "X-Api-Key", "<redacted>" );
Uri uri = builder.build( );
Log.e( "###", "uri =" + uri.toString( ) + "=" );

URL url = new URL( uri.toString( ));
HttpURLConnection connection =(HttpURLConnection) url.openConnection( );
connection.setRequestProperty("Accept", "application/json");
connection.setRequestMethod( "GET" );
connection.connect( );

InputStreamReader streamReader = new  InputStreamReader( connection.getInputStream( ));
BufferedReader reader = new BufferedReader( streamReader );
StringBuilder stringBuilder = new StringBuilder( );
String inputLine;

while( (inputLine = reader.readLine( )) != null )
	stringBuilder.append( inputLine );

reader.close( );
streamReader.close( );

String jsonText = stringBuilder.toString( );
Log.e( "###", "jsonText =" + jsonText );

HELP!

This is incorrect - these are not query parameters as I understand them.

The first is the API endpoint, so you likely want to use builder.appendPath("/api/version") instead.

The second, the HTTP/1.1 part, is not a parameter either, and I'm not sure why you have included it in the request. Unless I am missing something, this is implied by the builder.scheme("http").

1 Like

Thank you for your reply. I'll give the "appendPath" a try tomorrow.

As for the "HTTP/1.1" - I was trying, quite literally, everything.

1 Like

FWIW, this is what works:

	Uri.Builder builder = new Uri.Builder( );
	builder.scheme( "http" );
	builder.encodedAuthority( "172.16.0.150:5000/api/version" );
	Uri uri = builder.build( );
	Log.e( "###", "uri =" + uri.toString( ) + "=" );
	URL url = new URL( uri.toString( ));

	HttpURLConnection httpConnection =(HttpURLConnection) url.openConnection( );
	httpConnection.setRequestProperty("Accept", "application/json");
	httpConnection.setRequestProperty( "X-Api-Key", "<redacted>");
	httpConnection.setRequestMethod( "GET" );

	httpConnection.connect( );

	InputStreamReader streamReader = new  InputStreamReader( httpConnection.getInputStream( ));
	BufferedReader reader = new BufferedReader( streamReader );
	StringBuilder stringBuilder = new StringBuilder( );
	String inputLine;

	while( (inputLine = reader.readLine( )) != null )
	stringBuilder.append( inputLine );

	reader.close( );
	streamReader.close( );

	String jsonText = stringBuilder.toString( );
	Log.e( "###", "jsonText =" + jsonText );