How to set parameters in a GET request in Java - java

So I want to send a GET request with parameters. But it only seems to have conventions for the url you send the request to. Unlike the POST request, I see no way to pass parameters in it.
How I send the GET request now, without parameters (might be wrong):
String url = "http://api.netatmo.net/api/getuser";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
Log.v(TAG, ("\nSending 'GET' request to URL : " + url));
Log.v(TAG, ("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
Log.v(TAG, (response.toString()));
How I send the POST request with parameters:
String url = "https://api.netatmo.net/oauth2/token";
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 = "grant_type=password&client_id=myid&client_secret=mysecret&username=myusername&password=mypass";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
Log.v(TAG, "\nSending 'POST' request to URL : " + url);
Log.v(TAG, "Post parameters : " + urlParameters);
Log.v(TAG, "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
Log.v(TAG, response.toString());
access_token = response.substring(17, 74);
refresh_token = response.substring(93,150);
getRequest = "/api/getuser?access_token=" + access_token + " HTTP/1.1";
Log.v(TAG, access_token);
Log.v(TAG, refresh_token);
Log.v(TAG, getRequest);

As per the HTTP specification GET supports only path params or url params and hence you cannot put the params in HTTP request body as you do in POST request.
As Sotirios mentioned in the comments, technically you can still push params in the GET body, but if the APIs are respecting the specs, they will not provide you a way to do it.

Have you tried to add the query params to the request java.net.URL?
String url = "http://api.netatmo.net/api/getuser?access_token=" + access_token;
URL obj = new URL(url);

I was encountering the same problem, trying this:
String bla = "http://api.netatmo.net/api/devicelist?access_token=" + AUTH_TOKEN;
URL url = new URL(bla);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
String message = "";
while ((line = reader.readLine()) != null)
{
message += line;
}
I got an exception that the syntax was not correct. When I changed the syntax (by for example encoding with UTF 8) the API would just return errors (like 404 not found...).
I finally got it working using this:
try
{
System.out.println("Access Token: " + AUTH_TOKEN);
String url = "http://api.netatmo.net/api/devicelist";
String query = "access_token=" + URLEncoder.encode(AUTH_TOKEN, CHARSET);
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", CHARSET);
InputStream response = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response));
String line = "";
String message = "";
while ((line = reader.readLine()) != null)
{
message += line;
}
return message;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Note: CHARSET = "UTF-8"

Turns out the url the API provided confused me greatly. I fixed the url and it works now.

Related

Unable to catch JSON response from URL

I was trying to make a request which would return JSON format response.But the output doesnt seem to be in json format.Please help.
String url = "http://httpbin.org/ip";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
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();
//print in String
System.out.println(response.toString());
//Read JSON response and print
JSONObject myResponse = new JSONObject(response.toString());
Seems like the link is corrupted and so getting the wrong output

Access website through vpnbook.com

I am working on application to access a web page through vpnbook.com.
My code is sending post request to URL "https://webproxy.vpnbook.com/includes/process.php?action=update" with post body as "u=yahoo.com&webproxylocation=random"
i am getting response code 302. and HTTP response header contains location
"Location=[http://www.vpnbook.com/webproxy]"
But same request was getting correct correct result when opening through web browser.
result contains header response
"Location:https://usproxy.vpnbook.com/browse.phpu=DWnjEwVwhlG5GQhW&b=0&f=norefer"
please tell me what is going wrong in my code.
try{
URL url = new URL("https://webproxy.vpnbook.com/includes/process.php?action=update");
HttpsURLConnection c = (HttpsURLConnection) url.openConnection();
c.setRequestProperty("User-Agent", USER_AGENT);
c.setRequestProperty("Accept-Language", ACCEPT_LANG);
c.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
c.setRequestProperty("Host", "webproxy.vpnbook.com");
c.setRequestProperty("Origin", "http://www.vpnbook.com");
c.setRequestProperty("Referer", "http://www.vpnbook.com/webproxy");
c.setRequestMethod("POST");
c.setDoInput(true);
c.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(c.getOutputStream());
wr.writeBytes("u=yahoo.com&webproxylocation=random");
wr.flush();
wr.close();
int responseCode = c.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
System.out.println("Response headers : " + c.getHeaderFields());
Map<String, List<String>> resHdr = c.getHeaderFields();
if( resHdr.containsKey("Set-Cookie") ){
cookies=resHdr.get("Set-Cookie").toString();
cookies = cookies.replaceAll("\\[|\\]", "");
System.out.println(cookies);
}
BufferedReader in =
new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
}catch(Exception ex) { ex.printStackTrace(); }

Push notifications using google cloud messaging (gcm) in ios issue

I am trying to send notification message for IOS through GCM from JAVA. That time i am getting one error with 400 status code Bad Request. Below i have mentioned my JAVA code...
String apiKey = "xxxxxxxxxxxxxxxxxxxx"; // Put here your API key
String GCM_Token = regid; // put the GCM Token you want to send to here
String notification = "{\"sound\":\"default\",\"badge\":\"2\",\"title\":\"default\",\"body\":\"Test Push!\"}"; // put the message you want to send here
String messageToSend = "{\"to\":\"" + GCM_Token + "\",\"notification\":" + notification + ",\"content_available\" : true}"; // Construct the message.
TRY{
URL url = new URL("https://android.googleapis.com/gcm/send");
System.out.println("Message"+messageToSend);
// Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Set the headers
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Authorization", "key=" + apiKey);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.write(messageToSend.getBytes("UTF-8"));
//Send the request and close
wr.flush();
wr.close();
//Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
System.out.println("Message : " + conn.getResponseMessage());
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//Print result
System.out.println(response.toString()); //this is a good place to check for errors using the codes in http://androidcommunitydocs.com/reference/com/google/android/gcm/server/Constants.html
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
please give me the suggestion.Thanks in advance.

In HttpURLConnection Why don't JSONObject as Params work but String as Params are working

I am using HttpUrlConnection to post some data to my server here is the function:
private String register(String myurl) throws IOException {
String resp = null;
try {
JSONObject parameters = new JSONObject();
// parameters.put("jsonArray", ((makeJSON())));
parameters.put("key", "key");//getencryptkey());
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setReadTimeout(10000 /* milliseconds *///);
// conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
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();
System.out.println("strngbuffr" + response.toString());
resp = response.toString();
} catch (Exception exception) {
System.out.println("Exception: " + exception);
}
System.out.println("rsp"+ resp.toString());
return resp.toString();
}
I get the response code as 200, which means connection is okay however I get empty variables on PHP side, what can be wrong here?
Earlier I was sending a JSON array too but just to test functonality I commented that out now I am only sending one variable key as "key"
Its amazing to see, this sample code works - sans the JSON array and the key value pairs:
private String sendPost(String url) throws Exception {
String USER_AGENT = "Mozilla/5.0";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String urlParameters ="sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
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("rvsp"+response.toString());
return response.toString();
}
So it boils down to replacing this:
JSONObject parameters = new JSONObject();
parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON())));
parameters.put("key", getencryptkey());
by this:
String urlParameters ="jArr="+makeJSON()+"Key="+getencryptkey();
and I am still curious.
I reckon the problem here is not at the Java side, If the parameters is of fixed type like in json in your case, the JSON Object as POST params method will work if collected this way on the php side:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
print_r($obj);
print_r("this is a test response");
?>
The problem here was not with the Java side, it was with the php side, the JSON Object as POST params method will work if collected this way on the php side:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
print_r($obj);
print_r("this is a test");
?>

OpenId Connect to Google gives me Http 400

Im trying to access to Google APIs using OAuth 2.0
but i always receive the http 400 when i try to get the token
I'm using Tomcat8 with Java SDK 8
And i don't know what is wrong.
private void sendPost(
final String code,
final String clientId,
final String clientSecret,
final String redirectUri,
final String grantType) throws Exception {
String url = "https://accounts.google.com/o/oauth2/token";
StringBuffer strb = new StringBuffer();
strb.append("code=" + code);
strb.append("&client_id=" + clientId);
strb.append("&client_secret=" + clientSecret);
strb.append("&redirect_uri=" + redirectUri);
strb.append("&grant_type=" + grantType);
String urlParameters = strb.toString();
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", String.valueOf(urlParameters.length()));
// Send post request
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());
}
My output is the following it seems that all parameters are ok.
Sending 'POST' request to URL : https://accounts.google.com/o/oauth2/token
Post parameters : code=<code>.InoAg9JcLi0boiIBeO6P2m94pmoskwI&client_id=<clientid>.apps.googleusercontent.com&client_secret=<secret>&redirect_uri=http://localhost:8080/Oauth/connect&grant_type=authorization_code
Response Code : 400
you'd want to url-encode the parameters
I don't think Google supports redirect_uri's pointing to "localhost" anymore so that would suggest that you got the "code" on a different redirect_uri than the one presented on the token endpoint request

Categories