I want to get JSON from web service using POST method. This is my code, which I've tried:
public class Test {
public static void main(String[] args) {
String urlStr = "http://dev.crnobelo.mk/web_services/index.php/index/horoscope";
String[] paramName = { "horoscope_sign" };
String[] paramVal = { "oven" };
try {
String output = httpPost(urlStr, paramName, paramVal);
System.out.println("Result: " + output);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
// Create the form content
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() != HttpURLConnection.HTTP_OK) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
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();
}
}
So, as result I should get JSON text, but i don't get anything, also no errors. Is my code wrong, or this service is not working, or something else...?