How to Call JAVA GET request with JSON Array as a parameters - java

Am trying to create a JAVA GET Http connection request with JSON Array data as shown below. where as the same code works with out any parameter (i.e. ?data={..})
String myurl = "https://myserver.com/test/api/v1/parameter?data={"username":{"name":"testusername"},"salary":{"sal":"56748","bonus":"3221"},"category":{"cat":"CATA"}}";
String newmyurl = myurl.replaceAll("\"","\\\"");
log.info("**newmyurl*** "+newmyurl);
URL url = new URL(newmyurl);
log.info("**URL*** "+url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// By default it is GET request
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode(); // Code breaks here nothing errors in log
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String output;
StringBuffer sb = new StringBuffer();
while ((output = in.readLine()) != null) {
sb.append(output);
}
in.close();
//printing result from response
log.info("****return string****"+sb.toString());

To escape characters in a URL, use URLEncoder:
String myjson = "{\"username\":{\"name\":\"testusername\"},\"salary\":{\"sal\":\"56748\",\"bonus\":\"3221\"},\"category\":{\"cat\":\"CATA\"}}";
String myurl = "https://myserver.com/test/api/v1/parameter?data=" + URLEncoder.encode(myjson, "UTF-8");

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

Sending a JSON formatted string through HttpUrlConnection

I've done some research on using HttpUrlConnect and most examples I've seen uses either
a) a params string which looks like this:
paramString = "param1=someParam&param2=2ndparam&param3=3rdparam";
b) uses a put method to place the parameters:
JSONObject json = new JSONObject();
json.put("param1", "Parameter");
json.put("param2", "Parameter2");
json.put("param3", "Parameter3");
The format I want to send looks like this:
{
"grant_type":"password",
"username":"testuser#someid.com",
"password":"testPwd123$"
}
Is there a way for me to send a formatted JSON string instead of setting parameters or using a param string? The code I'm using to send my POST request looks like the following:
public static String PostRequest(String urlString, String token, String jsonString) throws IOException {
byte[] postData = jsonString.getBytes(StandardCharsets.UTF_8);
URL url = new URL(urlString);
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 ("Authorization", "Bearer " + token);
conn.setUseCaches(false);
try( DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
int responseCode = conn.getResponseCode();
System.out.println("POST response code: " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
I'm open to suggestions whether to use a different library, or if there are any code changes that I should make in order to take a JSON formatted string.

java how to receive web service response in JSON

i am new to web services i am calling a web service that should returns JSON with the folliwng code - the problem is i am getting the response in xml format
when i am trying the same parameters using google rest api - the response is in jSON
any ideas what i am doing wrong ?
public static String getSFData(String urlSuffix) throws MalformedURLException, ProtocolException , IOException
{
String header = "Basic XXXXX";
URL url = new URL("https://api2.successfactors.eu/odata/v2/"+urlSuffix);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("authorization",header);
connection.setRequestProperty("Content-Type", "application/json");
BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bf.readLine()) != null )
{
stringBuffer.append(line);
}
String response = stringBuffer.toString();
System.out.println("response"+response);
return response;
}
UPDATE
You could try the API URL like http://api2.successfactors.eu/odata/v2/User?
$format=json to get data in JSON.
Use StringBuilder instead of StringBuffer.
Try the following after set content type.
connection.connect();
int status = connection.getResponseCode();
switch (status) {
case 200:
BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bf.readLine()) != null) {
stringBuilder.append(line);
}
String response = stringBuilder.toString();
System.out.println("response : " + response);
}

JAVA: empty JSON in code, filled JSON in browser

I'm trying to get a json object from the url:
http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم
However, when I run my code with that url, I got an empty json, and when I'm request the url from my browser, the josn is filled.
what is wrong with my code?
URL url = new URL("http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
Scanner scan = new Scanner(is);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
And I tried also
// Create URL object
URL obj = new URL("http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم");
// Communicate with the URL by HTTP
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// Getting response data
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
The solution was to encode the url string before passing it to the URL constructor.
String urlstring = "http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم";
URLEncoder.encode(urlstring, "UTF-8");
URL url = new URL(urlstring);
Then continues with the previous code shown in the original post.
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
Scanner scan = new Scanner(is);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
And the moral is.. I should encode the url before I use it!
Try to use BufferedReader like this:
URL url = new URL("http://www.alfanous.org/jos2?action=search&unit=aya&fuzzy=True&query=حم");
URLConnection conn = url.openConnection();
BufferedReader br =new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}

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");
?>

Categories