REST API Client response in java encoding trouble - java

I have a problem with an API call response in java.
See below the API response of my request, server replies with content that is unreadable as text:
Here is my code:
String urlt = "xxxxxx";
URL url = new URL(urlt);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Accept-Encoding", "gzip");
conn.addRequestProperty("User-Agent", "okhttp/3.4.1");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
and an example of response headers:

With the following line, you tell the server that you are ready to accept a compressed response:
conn.addRequestProperty("Accept-Encoding", "gzip");
As shown in picture of response headers, the server obliges and gives you gzip-encoded (compressed) content.
But then you proceed to read the response, assuming it's just text... so yeah it prints as garbage in your console.
Either you remove that header above, or be ready to uncompress gzipped content.

Related

how to send push notification to the android device using FCM by java server?

I have write this code for send notification using fcm by java server code. But it is throwing exception Server returned HTTP response code: 500 for URL: https://fcm.googleapis.com/fcm/send
public static void pushFCMNotification(String userDeviceIdKey) throws Exception{
String authKey = AUTH_KEY_FCM; // You FCM AUTH key
String FMCurl = API_URL_FCM;
URL url = new URL(FMCurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key="+authKey);
conn.setRequestProperty("Content-Type","application/json");
JSONObject json = new JSONObject();
json.put("to",userDeviceIdKey.trim());
JSONObject info = new JSONObject();
info.put("title", "Notificatoin Title"); // Notification title
info.put("body", "Hello Test notification"); // Notification body
json.put("notification", info);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + json);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
/*OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();*/
}
According to the oficial documentation:
Errors in the 500-599 range (such as 500 or 503) indicate that there was an internal error in the FCM connection server while trying to process the request, or that the server is temporarily unavailable (for example, because of timeouts). Sender must retry later, honoring any Retry-After header included in the response. Application servers must implement exponential back-off.
source: https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream
However, make sure that the JSON request is properly formatted. Try to update your question with the json.toString() and check that your API key is still valid using the procedure described in: Checking the validity of a server key

Send http post request to URL with query string using HttpPost client in java

I need to send a post request to url which is formed as follows:
www.abc.com/service/postsomething?data={'name':'rikesh'}&id=45
Using HttpPost client in java, how can post request to such query strings
I could connect from javascript easily through ajax but from java client, it's failing.
(I know sending querystring in post request is stupid idea. Since I am connecting to someone else's server I cannot not change the way it is)
Here is one way to send JSON in a POST request using Java (without Apache libraries). You might find this helpful:
//init
String json = "{\"name\":\"rikesh\"}";
String requestString = "http://www.example.com/service/postsomething?id=45";
//send request
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
os.flush();
int responseCode = conn.getResponseCode();
//get result if there is one
if(responseCode == 200) //HTTP 200: Response OK
{
String result = "";
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
while((output = br.readLine()) != null)
{
result += output;
}
System.out.println("Response message: " + result);
}

HttpURLConnection always return error 500

i'm trying to run a soap request in a basic http request...naturally i tried with external tools the message and is correct, like the endpoint i'm using as targetUrl, the wsdl is in something like
http://00.00.00.00/a-ws/services/basic?wsdl
and my actual end point is
http://00.00.00.00/a-ws/services/basic.targetservice
and i'm using this last as target url
URL url = new URL(targetUrl);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
connection.setRequestProperty("SOAPAction", action);
connection.setRequestProperty("User-Agent", "myagent");
connection.setRequestProperty("Host", "localhost");
//connection.setRequestProperty("Content-Length", "" + Integer.toString(message.getBytes().length));
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
OutputStream wr = connection.getOutputStream ();
wr.write (message.getBytes());
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line=null;
StringBuffer response = new StringBuffer();
while( (line = rd.readLine()) != null) {
if (line!=null)
response.append(line);
}
rd.close();
return response.toString();
the raw message is tested with chrome plugin, the only thing i can't test is headers but the result is always an exception on getInputStream
java.io.IOException: Server returned HTTP response code: 500 for URL:
why?
It was a very stupid issue of encoding (like I was supposing)...i didn't escape double quote inside the message.
The evidence of problem was visible using a fake http server that just echo contents.
UPDATE:
Another thing nobody already pointed out is that is useful in case of exception to retrieve
connection.getErrorStream()
that contains the response in case of error!

404 Error when sending HTTP request through java

I seem to be getting a 404 error when sending a http post to a sinatra server. I am trying to make the server page the text I send to it, here's my code I think it may be something wrong with my server but I'm not sure:
private void sendInfo() throws Exception {
//make the string and URL
String url = "http://localhost";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
//send post
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'post' request to url: " + url);
System.out.println("Post parameters : " + urlParameters);
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();
//print result
System.out.println(response.toString());
}
and here is the sinatra server (ruby):
require 'sinatra'
get '/' do
'hello mate'
end
get '/boo' do
'trololo'
end
Could your problem be realated to trying to use a HTTPS (instead of HTTP) connections? I am looing at the use of HttpsURLConnection.
Since you're sending your HTTP request via POST, shouldn't your sinatra server routes bet post instead of get? Would explain why you're getting a 404. Something like this should sort it out:
require 'sinatra'
post '/' do
'hello mate'
end
post '/boo' do
'trololo'
end

Imgur API request using Java returns 400 status

I am trying to send a GET request to the Imgur API to upload an image.
When I use the following code I receive a 400 status response from the Imgur server - which, according to the Imgur error documentation, means I am missing or have incorrect parameters.
I know the parameters are correct as I have tested them directly in the browser URL (which successfully uploads an image) - so I must not be adding the parameters correctly within the code:
private void addImage(){
String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode("http://www.lefthandedtoons.com/toons/justin_pooling.gif", "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("myPublicConsumerKey", "UTF-8");
// Send data
java.net.URL url = new java.net.URL("http://api.imgur.com/2/upload.json");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Logger.info( line );
}
wr.close();
rd.close();
}
This code is based on the API examples provided by Imgur.
Can anyone tell me what I am doing wrong and how I may resolve the problem?
Thanks.
In this sample, imgur service returns 400 Bad Request status response with a non-empty body because of incorrect API key. In case of non successful HTTP response you shold read the response body from an error input stream. For example:
// Get the response
InputStream is;
if (((HttpURLConnection) conn).getResponseCode() == 400)
is = ((HttpURLConnection) conn).getErrorStream();
else
is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
And, by the way your example is POST, not GET, because you are sending the parameters in the request body instead of the URL.

Categories