IHS (Apache) 400 Error when adding UUID header to HttpUrlConnection - java

I need to add a header ("correlationIdHeader") to a GET Request using Java's HttpUrlConnection. However the server (IBM Http Server - built on Apache) answers with a 400 Error and the following info:
Request header field is missing ':' separator
My code:
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("correlationIdHeader", UUID.randomUUID().toString());
conn.setRequestMethod(HttpMethod.GET.name());
conn.setRequestProperty("Accept", contentType);
int responseCode= conn.getResponseCode();
Any idea what could be happening here?
EDIT: it has to do with UUID.randomUUID().toString(). I don't know why but it doesn't like UUID's format. Why?

Related

RESTFUL jetty service returning 403 error java

I am facing this HTTP 403 Forbidden response from a https REST service when I am trying to call it from my java code. Can you kindly let me know if I am missing something here?
Please note that the server returns the expected data when I trigger the request from any browser / SOAPUI/ Chrome Postman clients.
2 peer certificates are used - as shown in the ssl info from soapui after the request is sent.
The code snippet is attached. [The headers I set in the code are taken from the request header I found from the successful requests]
HttpsURLConnection connection = (HttpsURLConnection)new URL("https://server address").openConnection();
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
connection.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1");
connection.addRequestProperty("Connection", "Keep-Alive");
connection.addRequestProperty("Cache-Control","no-cache");
connection.setRequestMethod("GET");
connection.connect();
System.out.println("Response Code : " + connection.getResponseCode()+" "+connection.getResponseMessage());
Response Code : 403 Forbidden
Can you please check the Server URL if it is in the Java Acceptable format?
Sometimes java need escape characters to recognize strings correctly.
This question: What are all the escape characters? , can help you to check if you are using any of those characters. Also check if the conversion in the function is done properly.
Also, if you have more complex URL, consider to use java.net.URL .
Finally, check the user agent parameter Setting user agent of a java URLConnection .
Thanks for your response. The issue is with session cookie to be used for the connection. We are able to connect and get the response back with response code HTTP 200 once the cookie with JSESSIONID is passed as a header. Thanks again.

PORT Change in error case: HttpURLConnection

I am consuming API using HttpURLConnection in my android application and its running fine but if I get response code except then 200 ok (like 404, 500) my port is changing when I hit next request after error response code:
my code for android request is below and wireshark log as well:
try {
url = new URL(path_url + apiMsg); //in the real code, there is an ip and a port
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept","*/*");
}
Please refer wireshark log:
https://files.fm/u/w7umrwwk
So how to avoid PORT change in error scenario as well like in success 200 case, so that we continue to run on the same PORT.
read about sun.net.http.errorstream.enableBuffering in HttpURLConnection source code.
By default when response code is >= 400 then the connection is closed.
It is a clean though not so efficient way of handling error streams.
Instead of setting obscure system properties to handle this, it would be better to move to a proper http client like apache.

Server returned HTTP response code: 500. Java app

I am making simple request from Spring Boot app to URL.
URL url = new URL("http://...:8001/api/meta");
HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
int code = urlConnect.getResponseCode();
...
code = 500. Then an error occurs:
Server returned HTTP response code: 500.
Also urlConnect.getErrorStream = null
If I put the url to browser then I successfully get json.
What should be done to fix the issue?
I have added:
urlConnect.setRequestProperty("Accept", "application/json");
then I can successfully get the response.

JAVA POST request and then redirect to it?

What I need to do is send POST request to specific URL with two parameters and when the request is sent, I need to redirect user to that link so that he would be able to access functionality.
So far, what I have managed to do from various examples is this:
private void postRemoteAdvisoryLink() throws IOException {
URL obj = new URL(KdrmApplicationContext.getRemoteAdvisoryUrlPath());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(60000);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// For post only - start
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(("?auth=ssor&TransportKey=" + ssorTransportKey).getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
}
The problem is that now I get connection time out when trying to execute OutputStream os = con.getOutputStream(); line. Also, I still have no idea how to redirect user when request is completed.
Any ideas?
Using the basic Java URL classes would require you to manually handle the details of HTTP protocol - it's better to use libraries like Apache Http Components, as they deal with the underlying protocols for you. Some examples including POST requests can be found on their website.
Given the original question, the Timeout is likely related to host not responding or your Java application being unable to connect to given URL (due to no proxy configuration for example).
If you want to redirect a request based on the answer, you need to check the response headers and http status - if the status is 302, then there should be a header called Location, which will contain the URL you should make another request to.
Before getting an OutputStream, also make sure to set the Content-Length header (and ideally the Content-Type header as well).

HTTP 403 while executing a PUT request

I am creating a django rest api, and I'm trying to send JSON data via PUT request from an Android device, using HttpUrlConnection.
URL url = new URL(myurl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("PUT");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
Log.v("Apiput", MainActivity.cookieManager.getCookieStore().getCookies().get(0).toString());
conn.connect();
if(conn.getResponseCode() != 200) {
return "" + conn.getResponseCode();
}
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
osw.write(put);
osw.flush();
osw.close();`
I know I have to send a csrf token, but I think that I'm sending it already.
By examining the META in my request I can see the csrf token both in headers and cookies:
'HTTP_COOKIE': 'csrftoken=3jLNzfLIu1P5dBH4WWwggHMH7oDQC7Rx;'
And in my android device i have a CookieManager that says that the csrf cookie has the same value.
V/Apiputīš• csrftoken=3jLNzfLIu1P5dBH4WWwggHMH7oDQC7Rx
I am getting a 403 (Forbidden) Http error besides the user is authenticated (I can make GET Requests)
[26/Sep/2015 00:16:04]"PUT /api/works/34/ HTTP/1.1" 403 58
With curl I am able to send the request without any problem, with the same user credentials.
I wonder if anyone can tell me what am I doing wrong.
Thanks.
You don't have to set the cookie if you're doing a JSON call to Django REST framework.
It would definitively help if you can provide the permissions associated to the view.

Categories

Resources