java - HttpURLConnection send header authorization -
i struggling send requests authorization header using httpurlconnection. error code 400 returned.
i successful okhttpclient requested not use dependencies.
here code:
public static string getrequserprofiles() throws ioexception { url url = new url(urlstring); httpurlconnection urlconnection = (httpurlconnection) url.openconnection(); urlconnection.setdooutput(true); urlconnection.setrequestmethod("get"); urlconnection.setrequestproperty("content-type", "application/" + "json"); urlconnection.setrequestproperty("authorization", "bearer " + management_token); urlconnection.connect(); if (urlconnection.getresponsecode() != 200) { throw new runtimeexception("failed : http error code : " + urlconnection.getresponsecode()); } string assembledoutput = ""; bufferedreader responsebuffer = new bufferedreader(new inputstreamreader( (urlconnection.getinputstream()))); string output; system.out.println("output server:\n"); while ((output = responsebuffer.readline()) != null) { system.out.println(output); assembledoutput = assembledoutput + output; } urlconnection.disconnect(); return assembledoutput; }
edit:
everything working -
the problem in:
urlconnection.setdooutput(true);
setdooutput(true) : declares sending body request. requests not require body, can set false or commented out. instead used post, patch, put etc... (requests require body).
also note:
urlconnection.setrequestmethod("get");
does not need declared if sending request (although left in code readability)
i suspect if include setdooutput(true) , no request method specified, method default post request.
i have developed library can use it.
https://github.com/kksingla/fetchjson
you can view code here if dont want use dependency
Comments
Post a Comment