I have to make a request to an api.
The curl that works is:
curl -u apiKey:pass -H "Accept: application/json" https://subdomain.chargify.com/portal/customers/id/management_link.json
and the java code that i have so far is:
String userpass = apiKey + ":" + pass;
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
URL url = new URL(stringUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setRequestProperty("Accept", "application/json");
uc.setRequestProperty("Authorization", basicAuth);
InputStream content = uc.getInputStream();
int status = uc.getResponseCode();
BufferedReader in = new BufferedReader (new InputStreamReader(content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
Every time i get a 401 response code.
What am I doing wrong?
Your request requires User Aunthentication. As the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. Check how you are generating and validating key
Related
I use command "curl -X DELETE --header 'Accept: application/json' 'http://10.10.1.29:8181/onos/v1/flows/application/olsrflow' -u karaf:karaf"
It Can work.
but use JAVA Code does't work.
have any problem in my JAVA code?
URL dc0ContrailUrl2 = new URL("http://10.10.1.29:8181/onos/v1/flows/application/olsrflow");
HttpURLConnection dcConn2 = (HttpURLConnection) dc0ContrailUrl2.openConnection();
dcConn2.setDoOutput(true);
String login = "karaf:karaf";
String content = URLEncoder.encode (login) ;
String basicAuth = "Basic " + new String(new Base64().encode(login.getBytes()));
dcConn2.setRequestProperty("Authorization",basicAuth);
dcConn2.setRequestProperty("Content-Type", "application/json");
dcConn2.setRequestMethod("DELETE");
BufferedReader in2 = new BufferedReader(new InputStreamReader(dcConn2.getInputStream()));
String inputLine2;
while ((inputLine2 = in2.readLine()) != null){ //while response is not null, assign response to inputLine and print inputLine
System.out.println(inputLine2);
}
in2.close();
error HTTP response code: 415
You did not add Accept type the same as curl. Add the following line and remove the Content-Type:
dcConn2.setRequestProperty("Accept", "application/json");
Typically it means that server does not support MediaType has been passed. You have to figure out what does it expect and setup it in your request accordingly.
I have an issue regarding OData querying with an Java Client.
If I use Postman, everything works as expected and I'm receiving a response from the web service with the metadata. But in my Java Client, which runs not on the SCP / HCP I'm receiving "400-Bad Request". I used the original Olingo libary.
I only used the $metadata Parameter, so there is no filter value or something else.
public void sendGet(String user, String password, String url) throws IOException, URISyntaxException {
// String userPassword = user + ":" + password;
// String encoding = Base64.encodeBase64String(userPassword.getBytes("UTF-8"));
URL obj = new URL(url);
URL urlToEncode = new URL(url);
URI uri = new URI(urlToEncode.getProtocol(), urlToEncode.getUserInfo(), urlToEncode.getHost(), urlToEncode.getPort(), urlToEncode.getPath(), urlToEncode.getQuery(), urlToEncode.getRef());
// open Connection
HttpURLConnection con = (HttpURLConnection) uri.toURL().openConnection();
// Basis Authentifizierung
con.setRequestProperty("Authorization", "Basic " + user);
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("Content-Type", "application/xml");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
response.append("\n");
}
in.close();
// print result
System.out.println(response.toString());
// Schließt eine Vorhandene Verbindung
con.disconnect();
in User is already the encoded value. by manipulating this one, i'm receiving an authorization error, so already tested.
May somebody can help me in that case :)
Thanks in advance.
Tim
So I solved it by myself.
i added the statement con.setRequestProperty("Accept", "application/xml"); and it works fo me.
Maybe it could help somebody else.
I am using the following code to perform POST requests on a REST API. It is all working fine. What I am being unable to do is after POST is successful the API returns response JSON in body with headers, this JSON has information which I require. I am unable to get the JSON response.
I need this response as this response includes the ID generated by DB. I can see the response while using REST Client plugin of firefox. Need to do implement the same in Java.
String json = "{\"name\": \"Test by JSON 1\",\"description\": \"Test by JSON 1\",\"fields\": {\"field\": []},\"typeDefinitionId\": \"23\",\"primaryParentId\": \"26982\"}";
String url = "http://serv23/api/contents";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//Setting the Request Method header as POST
con.setRequestMethod("POST");
//Prepairing credentials
String cred= "user123:p#ssw0rd";
byte[] encoded = Base64.encodeBase64(cred.getBytes());
String credentials = new String(encoded);
//Setting the Authorization Header as 'Basic' with the given credentials
con.setRequestProperty ("Authorization", "Basic " + credentials);
//Setting the Content Type Header as application/json
con.setRequestProperty("Content-Type", "application/json");
//Overriding the HTTP method as as mentioned in documentation
con.setRequestProperty("X-HTTP-Method-Override", "POST");
con.setDoOutput(true);
JSONObject jsonObject = (JSONObject)new JSONParser().parse(json);
OutputStream os = con.getOutputStream();
os.write(jsonObject.toJSONString().getBytes());
os.flush();
WriteLine( con.getResponseMessage() );
int responseCode = con.getResponseCode();
Get the input stream and read it.
String json_response = "";
InputStreamReader in = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(in);
String text = "";
while ((text = br.readLine()) != null) {
json_response += text;
}
I'm trying to send a PUT request from a Java app to a server. I successfully send GET, POST and DELETE requests but the PUT one won't succeed (I'm getting a 401 Error with the code below, 405 Error with an other code using the HttpPut of the apache package).
I'm using java.net.HttpURLConnection, here is a small region of my code :
URL obj = new URL(urlPost);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add request header
con.setRequestMethod(typeRequest); //typeRequest = PUT
String credentials = adminOC + ":" + pwdOC;
String encoding = Base64.encode(credentials.getBytes("UTF-8"));
con.setRequestProperty("Authorization", String.format("Basic %s", encoding));
if (!typeRequest.equals("GET")){
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(postParam);
wr.flush();
}
}
if (con.getResponseCode() == 200){
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
}
}
I tried sending my PUT parameters the "POST" way and also directly in the URL.
It seems to be an error from my Java code and not from the server because I tried to do the PUT request with cURL and it worked.
Thanks for reading, I hope you will be able to give me some hints to debug the problem.
What is missing in your code is con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
I want to integrate login with gmail as well as login with facebook on our website, so that without a new signup user can create his/her account on our website. Its a gwt with java based website. I have tried some codes and getting error java.io.IOException: Server returned HTTP response code: 401 for URL: https://accounts.google.com/o/oauth2/token and I am totally unaware why i am getting this error.
I have used thisdoc for code. Any help in why actually I am getting this error. have i missed something? any help in it.
Obviously it's Unauthorized(401)..You must have to give client_id and client_secret and also each request to the Gmail API requires an access token.
try this code at your redirected method
String code = request.getParameter("code");
String urlParameters = "code=" + code + "&client_id="
+ CLIENT_ID + "&client_secret="
+ CLIENT_SECRET + "&redirect_uri="
+ REDIRECT_GMAIL_URI
+ "&grant_type=authorization_code";
URL url = new URL("https://accounts.google.com/o/oauth2/token");
URLConnection urlConn = url.openConnection();
urlConn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
urlConn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line, outputString = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
JsonObject json = (JsonObject) new JsonParser().parse(outputString);
String access_token = json.get("access_token").getAsString();
url = new URL(
"https://www.googleapis.com/oauth2/v1/userinfo?access_token="
+ access_token);
urlConn = url.openConnection();
outputString = "";
reader = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
System.out.println(outputString);