HttpUrlConnection PATCH request using Java - java

I am trying to do a http PATCH request but I always get the 404 error, so maybe the settings of my connection are not correct:
URL url = new URL("MyPath");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("X-HTTP-Method-Override", "PATCH");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod("POST");
JsonObject jo = createMyJson();
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(jo.toString());
out.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
I get the 404 error, Not found. When doing the same request using Postman, this is working..
Thank you for your help.

Not all servers support X-HTTP-Method-Override. In that case your last resort is (if you are not using a decent HTTP client) to hack the URLConnection object.
I posted a complete solution here on SO, check it out.

Related

How to post request in java to get the response in JSON

I want to post the request in same formate.
POST /mga/sps/oauth/oauth20/token HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic aaabbbCCCdddeeefffGGG
client_id=xxx&client_secret=yyy&grant_type=authorization_code
&code=3v6MJzt9vKtRkxpTFnkJG3IyspWC2k
&redirect_uri=xyz%2Ffolder
I have Implemented but getting bad request and unable to print the post content what I am sending I also want to get the json response after sending this request.
String urlParameters = "grant_type=authorization_code"+"&redirect_uri="+session.getAttribute("redirect_uri")+"&code_verifier="+session.getAttribute("codeVerifier")+"&code="+session.getAttribute("code")+"&state="+session.getAttribute("state");
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
URL url = new URL( "https://example/oauth20/token" );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postDataLength ));
conn.setRequestProperty("Host","example.com");
conn.setRequestProperty("Authorization","clientID=xyz");
conn.setUseCaches(false);
DataOutputStream wr = new
DataOutputStream(conn.getOutputStream());
wr.write(postData);
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
conn.disconnect();
You have multiple options.
You can start with Java HTTP Client - Refer
The HTTP Client was added in Java 11. It can be used to request HTTP
resources over the network. It supports HTTP/1.1 and HTTP/2, both
synchronous and asynchronous programming models, handles request and
response bodies as reactive-streams, and follows the familiar builder
pattern.
Apache HttpClient - Refer
RestTemplate - Refer
JAX-RS Client - Example
Spring 5 WebClient - Example
OkHttpClient - Example
Comparison

How can I send POST parameters with HttpURLConnection POST in java?

I am not familiar with https requests so please take it easy on me.
I want to make a post call and retrieve a token for a url. The url is something like:
/auth/token?param1=value1&param2=value2&param3=value3&param4={{value4}}&param5={{value5}}
I make the post
HttpURLConnection conn = (HttpURLConnection) authentication.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestMethod("POST");
but in order to get the response I have to send the parameters.
I've tried to write the url params as string to the connection outputstream but it doesnt work.
Any help is appreciated.

Authorization for Spotify API in Java HttpURLConnection

I'm relatively new to using http and APIs but I was trying to use HttpURLConnection in Java to connect to the Spotify API. I managed to get a GET to work but I can't figure out how to make the authorization work in order to access other materials. Here's my code, can anyone see what I'm doing wrong? It's returning a 400 response code.
URL url = new URL("https://accounts.spotify.com/api/token?grant_type=client_credentials");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Authorization", Base64.getEncoder().encodeToString("Basic bdfc603f24c54078a7365d3af39c2aed:<ClientSecret>".getBytes()));
You're missing the Content-Type, see my example.
URL url = new URL("https://accounts.spotify.com/api/token?grant_type=client_credentials");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.setRequestProperty("Authorization", "Basic MDg4ZDc=");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

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.

Sometimes HttpURLConnection.getInputStream executes too slowly

We have next code.
Sometimes we should wait 10-20-40 seconds on the last line.
What can be the problem?
Java 1.4
URL url = ...;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.connect();
OutputStream out = conn.getOutputStream();
ObjectOutputStream outStream = new ObjectOutputStream(out);
try
{
outStream.writeObject(objArray);
}
finally
{
outStream.close();
}
InputStream input = conn.getInputStream();
UPDATED:
Next code fixes the problem IN ECLIPSE.
But it still DOES NOT WORK via Java WebStart:(
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
System.setProperty("http.keepAlive", "false"); //<---------------
conn.connect();
But why?
UPDATED one more time!
Bug was fixed! :)
We worked with connections not in one class but in two.
And there is following line in the second class:
URL url = ...
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Length", "1000"); //<------------
conn.connect();
Note:
setRequestProperty("Content-Length", "1000") is root cause of the problem.
'We had a similar issue which is caused by buggy keep-alive in old Java. Add this before connect to see if it helps,
conn.setRequestProperty("Connection", "close");
or
System.setProperty("http.keepAlive", "false");
Had the same problem, found out it was caused by IPv6.
You Disable it from code using:
System.setProperty("java.net.preferIPv4Stack" , "true");
You can also disable it via the command line using : g-Djava.net.preferIPv4Stack=true
Try it with an IP address. To see if it's a DNS problem.
I had same problem, so i change to HTTPClient from Apache, follow a example:
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("www.myurl-to-read");
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(8000)
.setConnectTimeout(10000)
.setConnectionRequestTimeout(1000)
.build();
request.setConfig(requestConfig);
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
The problem can be something from network sub layer... Should be hard to find it.
But what about the setReadTimeOut() with low value and a while loop?
One thing I would guess is that your DNS server isn't responding well.
Can you experiment with changing symbolic domain names to numeric IP addresses before you start? Or can you do each request twice (just for experimentation) and see if the first request is significantly slower than the second?
Google has put up a DNS server at (among others) 8.8.8.8 . They claim it's faster than most other DNS servers. Give that a try!

Categories

Resources