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);
}
Related
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");
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);
}
Hello I was wondering if somebody could help me with the following, I have a database that is currently populated. I used to call it using the http client and it worked fine but now I'm trying to update the code since its been deprecated to use the httpurlconnection but i have no success. I ve looked up some tutorials and tried a few thing but it doesn't seem to be working. the database is called through a php file and returns it in a json format.If i were to call the php file from my browser the response is the following: [{"id":"15","logo":"logo url","title":"title"}]
The error that I get on the console is the following:java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
Which its not making much sense to me since the script pulls information
I have the following code, i left the commented section just in case i need any of it, It also includes the old way i used to call the DB Thank you!:
public void loadNews(){
InputStream is = null;
String result = "";
ArrayList<NameValuePair>();
try {
URL url = new URL("http://databasecall.php");
//HttpClient httpclient = new DefaultHttpClient();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("Content-length", "0");
//urlConnection.setUseCaches(false);
//urlConnection.setAllowUserInteraction(false);
//urlConnection.setConnectTimeout(15000);
//urlConnection.setReadTimeout(15000);
//urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
Log.i("Tag:", Integer.toString(responseCode)); //tag 200
//HttpPost httppost = new HttpPost("http://databasecall.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = httpclient.execute(httppost);
//HttpEntity entity = response.getEntity();
//is = entity.getContent();
/*}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}*/
//convert response to string
//try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.i("Tag:", result);
}
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
Updated API
try {
String urlParameters = "name=toni&class=one¶m3=ok";
byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
int postDataLength = postData.length;
String request = "http://rocks.php";
URL url = new URL(request);
HttpURLConnection cox = (HttpURLConnection) url.openConnection();
cox.setDoOutput(true);
cox.setDoInput(true);
cox.setInstanceFollowRedirects(false);
cox.setRequestMethod("POST");
cox.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
cox.setRequestProperty("charset", "utf-8");
cox.setRequestProperty("Content-Length",
Integer.toString(postDataLength));
cox.setUseCaches(false);
OutputStreamWriter writer = new OutputStreamWriter(
cox.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(
cox.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
} catch (Exception e) {
result = e.toString();
Sucess = false;
e.printStackTrace();
}
I have to pass a token as part of validation for each GET request to access RESTful web service. Below is the code I'm using it to access REST api:
public static String httpGet(String urlStr, String[] paramName, String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
if (conn.getResponseCode() != 200) {
System.out.println("Response code: "+conn.getResponseCode());
throw new IOException(conn.getResponseMessage());
}
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
I can't see any such method to set Header conn.setHeader() provided for HttpsURLConnection. It should be something like X-Cookie: token={token}; please help me to find a way to set header.
You can use:
conn.addRequestProperty("X-Cookie", "token={token}");
or setRequestProperty() also works
You are already setting headers on your request in your code when you do the following:
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
I.e. if the service you are communicating with requires that you send your token in the "X-Cookie" header you can simply do the same for that header:
conn.setRequestProperty("X-Cookie", "token={token}");
I've modified the following code from an example on the internet. Currently it POSTs and returns the response line by line. How can I modify the code so it returns the entire response in one line, so I can parse it more easily.
static void updateIp() throws MalformedURLException, IOException {
String urlParameters = "name=sub&a=rec_edit&id=9001";
URL url = new URL("http://httpbin.org/post");
URLConnection con = url.openConnection();
con.setDoOutput(true);
BufferedReader reader;
try (OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream())) {
writer.write(urlParameters);
writer.flush();
String line;
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
reader.close();
}
Any help would be greatly appreciated!
You can't determine how many lines the URL response will be over, so you need to join them all together yourself in one line using StringBuilder:
static void updateIp() throws MalformedURLException, IOException {
String urlParameters = "name=sub&a=rec_edit&id=9001";
URL url = new URL("http://httpbin.org/post");
URLConnection con = url.openConnection();
con.setDoOutput(true);
BufferedReader reader;
try (OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream())) {
writer.write(urlParameters);
writer.flush();
String line;
StringBuilder urlResponse = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((line = reader.readLine()) != null) {
urlResponse.append(line);
}
String response = urlResponse.toString();
System.out.println(response);
}
reader.close();
}
The response string variable will now contain all the output in a single line.