I got a strange task: to connect to webserver using Java even though I'm a php programmer. I used to program Java back at the university but it's been good few years since.
I took a code sample from stack-overflow. It runs fine, no compilation errors no exceptions, but, I don't see any outgoing connection when I sniff with Fiddler, and my server side script doesn't see any incoming connections either.
Any ideas of what can be wrong? Or, how do I debug this situation?
String urlParameters = "param1=a¶m2=b¶m3=c";
String request = "http://example.com/index.php";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
Related
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");
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.
We are sending HTTPURLRequest to server.
When we are sending English content its working fine.But, when we are sending Arabic language content we are getting
Server returned HTTP response code: 500
We had written below code
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(SendRequest.getBytes().length));
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
dataout.writeBytes(SendRequest);
dataout.flush();
dataout.close();
BufferedReader bufferreader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
When I use connection.getInputStream() I am getting 500 error
We are using utf-8 also.But, still getting the error
can any one help me
You can use a library to escape the special chars:
StringEscapeUtils.escapeJava("هولاء كومو")
This class is available on: Commons Lang from Apache
Hope this helps!
Check the HTTP Status Response Codes. An error happened on the server, so the diagnostics will need to be performed on the server, not on the client.
I've got a legacy application that writes to an OutputStream, and I'd like to have the contents of this stream uploaded as a file to a Servlet. I've tested the Servlet, which uses commons-fileupload, using JMeter and it works just fine.
I would use Apache HttpClient, but it requires a File rather than just an output stream. I can't write a file locally; if there was some in-memory implementation of File perhaps that might work?
I've tried using HttpURLConnection (below) but the server responds with "MalformedStreamException: Stream ended unexpectedly".
URL url = new URL("http", "localhost", 8080, "/upload");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
String boundary = "---------------------------7d226f700d0";
connection.setRequestProperty("Content-Disposition", "form-data; name=\"file\"");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestMethod("POST");
connection.setChunkedStreamingMode(0);
connection.connect();
OutputStream out = connection.getOutputStream();
byte[] boundaryBytes =("--" + boundary + "\r\n").getBytes();
out.write(boundaryBytes);
//App writes to outputstream here
out.write("\r\n".getBytes());
out.write(("--"+boundary+"--").getBytes());
out.write("\r\n".getBytes());
out.flush();
out.close();
connection.disconnect();
The PostMethod allows you to set a RequestEntity, which is an interface which you can implement. you just need to implement the RequestEntity.writeRequest method appropriately.
Or, if you want HttpClient to handle the multi-part stuff for you, you could use MultipartRequestEntity with a custom Part.
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!