Java Http request PUT : 401 unauthorized - java

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")

Related

Can't simulate Postman request in Java

I'm trying to login to a portal. It works using Postman. When I try the same request using plain Java or OkHttp the login fails and I will be redirected to the login page.
HttpUrl.Builder httpBuilder = HttpUrl.parse("https://test58.cashctrl.com/auth/login.html").newBuilder();
httpBuilder.addQueryParameter("JMCF_AUTH_EMAIL", "email");
httpBuilder.addQueryParameter("JMCF_AUTH_PASSWORD", "password");
Request request = new Request.Builder()
.url(httpBuilder.build())
.get()
.build();
I know the Url looks weird but it works this way using Postman or even simply use a browser.
Alternative with plain Java, which I tried:
Map<String, String> parameters = new HashMap<>();
parameters.put(PARAM_EMAIL, EMAIL);
parameters.put(PARAM_PASSWORD, PASSWORD);
URL url = new URL(LOGIN_URL + "?" + ParameterStringBuilder.getParamsString(parameters));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setInstanceFollowRedirects(true);
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine + "\n");
}
in.close();
con.disconnect();
System.out.println(status);
System.out.println(content.toString());
Postman must be doing something special or also a browser which I don't see.
I had the same issue, I got to know that Postman has "code" feature. Below the send button you can see the code option it will generate the code for you. There is a list of language to choose from and java is one of them. Do check that out. Also you must be missing the cookie, see the temporary headers in Postman add all in your code and do include the cookie one.
Thanks I hope it helps.

OData Bad Request 400 with Java Client

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.

Java http get request slower than postman get request

I'm trying to send a get request in order to get a website content.
When I'm using Postman it takes about 70-100 ms, but when I use the following code:
String getUrl = "someUrl";
URL obj = new URL(getUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
response.toString();
it takes about 3-4 seconds.
Any idea how to get my code work as fast as Postman?
Thanks.
Try to find a workaround for the while loop. Maybe that is your bottleneck. What are you even getting from your URL? Json object or something else?
Try http-request built on apache http api.
HttpRequest<String> httpRequest = HttpRequestBuilder.createGet(someUri, String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer())
.addDefaultHeader("User-Agent", "Mozilla/5.0")
.build();
public void send(){
String response = httpRequest.execute().get();
}
I higly recomend read documentation before use.

Android HttpURLConnection always unauthorized 401 response (Spring Boot REST API)

I am attempting to consume a REST API with an Android app I am developing in Android Studio. I have developed the API using Spring Boot. The issue:
Whenever I make a call to my API I am always returned a 401 Unauthorized response. "Pre-authenticated entry point called. Rejecting access."
I have configured my CORS as follows:
cors:
allowed-origins: "*"
allowed-methods: GET, PUT, POST, DELETE, OPTIONS
allowed-headers: "*"
exposed-headers:
allow-credentials: true
max-age: 1800
My api is running on localhost:8080, and I am making the requests from my device with my WLAN IPv4 address.
Such as: curl -v -X GET http://192.168.1.xx:8080/api/users
This returns a 200 OK response.
I am also able to call this in postman/DHC etc.. and receive a 200 OK response.
However, when I call this same address with HttpURLConnection through my android device, I receive a 401 response.
Noob developer here - any ideas as to what might be causing this would be greatly appreciated!
Edit to include my GET Request:
#Override
protected String doInBackground(String... params){
String stringUrl = params[0];
String result;
String inputLine;
try {
//Create a URL object holding our url
URL myUrl = new URL(stringUrl);
//Create a connection
HttpURLConnection connect =(HttpURLConnection)
myUrl.openConnection();
connect.setRequestMethod(REQUEST_METHOD); // GET
connect.setRequestProperty("Host", HOST);
connect.setRequestProperty("Connection", "keep-alive");
connect.setRequestProperty("Origin", ORIGIN);
connect.setRequestProperty("User-Agent", System.getProperty("http.agent"));
connect.setRequestProperty("Content-Type", CONTENT_TYPE);
connect.setRequestProperty("Accept", "*/*");
connect.setRequestProperty("Accept-Encoding", ACCEPT_ENCODING);
connect.setRequestProperty("Accept-Language", ACCEPT_LANGUAGE);
connect.setDoOutput(true);
connect.setDoInput(true);
//Connect to our url
connect.connect();
String responseMessage = connect.getResponseMessage(); // Unathorized
int responseCode = connect.getResponseCode(); //401
//Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(connect.getInputStream());
//Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
//Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
//Set our result equal to our stringBuilder
result = stringBuilder.toString();
}
catch(IOException e){
e.printStackTrace();
result = null;
}
return result;
}
Replace:-
InputStreamReader streamReader = new
InputStreamReader(connect.getInputStream());
With:-
InputStreamReader streamReader = new
InputStreamReader(connect.getErrorStram());
This will help you track why 401 then you can proceed solving that issue.
401-- is server side problem, Server is unable to process you request, check if you have to pass data in header or url as you are using get request

HTTP Get request to Challonge returns robots.txt

When sending a get request to try and retrieve a challonge bracket, I get the robots.txt file instead of the actual bracket. If I copy and paste the same url into my browser, I get the intended JSON bracket. I was wondering what I was doing wrong and how I could make it so that the following Java method actually returns the bracket instead of the metaname=robots text file.
public String httpGett(String url,String userAgent) throws Exception{
String USER_AGENT = userAgent;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
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);
}
in.close();
//System.out.println(response.toString());
return(response.toString());
}
For example, if the url I sent was
https://challonge.com/api/tournaments/example.json?include_matches=1&include_participants=1&api_key=[MY
API KEY]
And I typed the url into my browser I would get:
http://pastebin.com/4W4kmdJV
And if I used my Java method to send the get request I would get:
http://pastebin.com/ifYSSzu3
How can I get the correct bracket info from my Java method?
So I managed to figure out what I was doing wrong, kind of.
When I use:
https://api.challonge.com/v1/tournaments/example.json?include_matches=1&include_participants=1&api_key=[MYAPIKEY]
Instead of the previous link, the metaname=robots link stopped appearing and I got the correct bracket information.

Categories

Resources