I am having some problem when trying to access MySQL from Android via Servlet. What I am trying to do is check if the event exist in database by passing some value to servlet class. If no existing record, then perform DB insertion.
public void createEvent(Event event) {
String page;
JSONArray jsonArray;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(ENeighbourhoodActivity.URL + "checkEventExist");
List<NameValuePair> checkExistnvp = new ArrayList<NameValuePair>(3);
checkExistnvp.add(new BasicNameValuePair("eventName", event.getEventName()));
checkExistnvp.add(new BasicNameValuePair("eventX", event.getEventX()));
checkExistnvp.add(new BasicNameValuePair("eventY", event.getEventY()));
try {
post.setEntity(new UrlEncodedFormEntity(checkExistnvp));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
page = "{\'Events\':" + responseString + "}";
try {
JSONObject jsonObject = new JSONObject(page);
jsonArray = jsonObject.getJSONArray("Events");
int length = jsonArray.length();
if(length == 0){
// If no existing record, then perform DB insertion
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
And inside my servlet:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JSONArray jsonArray = new JSONArray();
PrintWriter out = response.getWriter();
if (request.getParameter("checkEventExist") != null) {
String eventX = request.getParameter("eventX");
String eventY = request.getParameter("eventY");
String eventName = request.getParameter("eventName");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/mydb", "root", "root");
PreparedStatement statement = con
.prepareStatement("SELECT * FROM event WHERE eventName = '" + eventName + "' AND eventX = '" + eventX + "' AND eventY = '"+ eventY + "'");
ResultSet result = statement.executeQuery();
while (result.next()) {
JSONObject eventInfo = new JSONObject();
eventInfo.put("eventName", result.getString("eventName"));
eventInfo.put("eventX", result.getString("eventX"));
eventInfo.put("eventY", result.getString("eventY"));
jsonArray.put(eventInfo);
}
}
catch (JSONException je) {
System.out.println(je.getMessage());
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
out.println(jsonArray.toString());
}
}
I not sure how should I pass and get name/value pairs into the doGet() in servlet. With this line:
post.setEntity(new UrlEncodedFormEntity(checkExistnvp));
It's how I pass value into the doPost(). But I need to pass it to doGet() instead. Any guides?
Thanks in advance.
You should use query parameters since HTTP GET does not allow sending entity in HTTP Body.
In order to send parameters for the HTTP GET, you should prepare a URL like this:
HttpGet request = new HttpGet(ENeighbourhoodActivity.URL + "checkEventExist?" +
"eventName=<eventName>&"+
"eventX=<eventX>&"+
"eventY=<eventY>");
HttpResponse response = client.execute(request);
And you shouldn't add any NameValuePair to the request
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to create a simple web service between my Android App and Java Servlet. The response that I return from the servlet is JSONObject but what I'm recieving in my Android app is boolean. The code for both the servlet and android is given.
ANDROID CODE
class ExecuteTask extends AsyncTask<Void, Void, Void> {
String param;
#Override
protected Void doInBackground(Void... params) {
try {
param = "param1=" + URLEncoder.encode(_username, "UTF-8") + "¶m2=" + URLEncoder.encode(_password, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
URL url = null;
try {
url = new URL(url_login);
} catch (Exception e) {
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = null;
try {
out = new PrintWriter(conn.getOutputStream());
out.print(param);
Log.d("Checking Params", param);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
String response = "";
Scanner inStream = null;
// Log.d("JSON", json.toString());
try {
int responseCode = conn.getResponseCode();
if(responseCode ==200){
// conn.setDoInput(true);
inStream = new Scanner(conn.getInputStream());
}else{
InputStream in = null;
in = conn.getErrorStream();
}
}catch (IOException e) {
e.printStackTrace();
}
while (inStream.hasNextLine()) {
response += (inStream.hasNextLine());
try {
json = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
try {
String s = json.getString("Login");
Log.d("MSG", s);
if (s != null) {
Intent intent = new Intent(LoginActivity.this, DashboardActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Log.d("Msg sent", s);
finish();
} else if (s.equals("fail")) {
Toast.makeText(context, "Unable to load the schedule", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
conn.disconnect();
}
return null;
}
}
RUNQUERY METHOD
public JSONObject RunQuery(String[] params, HttpServletRequest request, HttpServletResponse response) {
// System.out.println("The parameters are: " + params[0] + params[1] +
// params[2]);
String sql = "SELECT * FROM job_recommender.user where User_Name='"+ params[0] +"' AND password='"+ params[1] +"'";
// System.out.println("Our SQL Statement is " + sql);
JSONObject json = new JSONObject();
// JSONArray jArray = null;
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
if (rs.next()) {
System.out.println("This is RS" + rs);
JSONObject jObj = new JSONObject();
jObj.put("username", (new String(rs.getString("User_Name"))));
jObj.put("password", (new String(rs.getString("password"))));
System.out.println(jObj);
json.put("Login", jObj);
System.out.println(json.put("Login", jObj));
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("This is our JSON" + json);
response.setContentType("Content-Type=application/json");
response.setCharacterEncoding("charset=UTF-8");
PrintWriter out;
try {
System.out.println("response JSON" + json.toString());
out = response.getWriter();
out.println(json);
//response.getWriter().write(json.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
SERVLET
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.setContentType("text/html");
Enumeration paramNames = request.getParameterNames();
//System.out.println(paramNames);
String params[] = new String[2];
int i = 0;
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
System.out.println("Checking ParamNames" + paramName);
String[] paramValues = request.getParameterValues(paramName);
params[i] = paramValues[0];
ulogin.setUsername(params[0]);
ulogin.setPassword(params[1]);
// System.out.println(params[i]);
i++;
}
String name = ulogin.getUsername();
String password = ulogin.getPassword();
System.out.println("username" + name + "password" + password);
WebServiceDAO wdao = new WebServiceDAO(getServletContext());
wdao.RunQuery(params, request, response);
response.getWriter().append("Served at: ").append(request.getContextPath());
}
Can anyone tell me what I'm doing wrong here? I have tried every way I could think of to fix this. Any help would be useful to me.
There's a typo in your code
response += (inStream.hasNextLine());
Should probably be
response += (inStream.nextLine());
I want to get response after post data but it fails. I want to create a login system, I have successfully submited data to php file, everything is working fine now I want to get response from same function but I'm unable to know where the issue is.
Here is the Java function:
public class PostDataGetRes extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
postRData();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}
public void postRData() {
String result = "";
InputStream isr = null;
final String email = editEmail.getText().toString();
final String pass = editPass.getText().toString();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://website.com/appservice.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", email));
nameValuePairs.add(new BasicNameValuePair("stringdata", pass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
resultView.setText("Inserted");
HttpEntity entity = response.getEntity();
isr = entity.getContent();
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("first_name")+"\n\n";
//"User ID : "+json.getInt("user_id")+"\n"+
//"Name : "+json.getString("first_name")+"\n"+
//"Email : "+json.getString("email")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
resultView.setText("Done");
}
And here is php code:
if($id){
$query = mysql_query("SELECT first_name FROM users where email = '$id' ");
while($row=mysql_fetch_assoc($query)){
$selectedData[]=$row;
}
print(json_encode($selectedData));
}
Please help me I have tried so far but could not achieve any results. Please help me how can I get response from php file after query execution.
At first be sure you get correct JSON object from your website - try printing it as Toast.makeText(). As far the web browsers keep the html comments away, android gets it in response.
AsyncTask objects and classes aren't designed to be made the way u provided and also you can't make any UI operations in doInBackground(). AsyncTask is made in a way to not to block GUI.
Here is a not much different example how it uses methods you have in AsyncTask class:
class Logging extends AsyncTask<String,String,Void>{
JSONObject json=null;
String output="";
String log=StringCheck.buildSpaces(login.getText().toString());
String pas=StringCheck.buildSpaces(password.getText().toString());
String url="http://www.mastah.esy.es/webservice/login.php?login="+log+"&pass="+pas;
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Operation pending, please wait", Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.addHeader("User-Agent", "User-Agent");
HttpResponse response;
try {
response = client.execute(request);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line="";
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) {
result.append(line);
}
output=result.toString();
} catch (ClientProtocolException e) {
Toast.makeText(getApplicationContext(), "Connection problems", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Conversion problems", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(Void w) {
try {
json = new JSONObject(output);
if(json.getInt("err")==1){
Toast.makeText(getApplicationContext(), json.getString("msg"), Toast.LENGTH_LONG).show();
}else{
String id_user="-1";
Toast.makeText(getApplicationContext(), json.getString("msg"), Toast.LENGTH_LONG).show();
JSONArray arr = json.getJSONArray("data");
for(int i =0;i<arr.length();i++){
JSONObject o = arr.getJSONObject(i);
id_user = o.getString("id_user");
}
User.getInstance().setName(log);
User.getInstance().setId(Integer.valueOf(id_user));
Intent i = new Intent(getApplicationContext(),Discover.class);
startActivity(i);
}
} catch (JSONException e) {
}
super.onPostExecute(w);
}
}
PHP file content:
$data = array(
'err' => 0,
'msg' => "",
'data' => array(),
);
$mysqli = new MySQLi($dbhost,$dbuser,$dbpass,$dbname);
if($mysqli->connect_errno){
$data['err'] = 1;
$data['msg'] = "Brak polaczenia z baza";
exit(json_encode($data));
}
if(isset($_GET['login']) && isset($_GET['pass'])){
$mysqli->query("SET CHARACTER SET 'utf8';");
$query = $mysqli->query("SELECT banned.id_user FROM banned JOIN user ON user.id_user = banned.id_user WHERE user.login ='{$_GET['login']}' LIMIT 1;");
if($query->num_rows){
$data['err']=1;
$data['msg']="User banned";
exit(json_encode($data));
}else{
$query = $mysqli->query("SELECT login FROM user WHERE login='{$_GET['login']}' LIMIT 1;");
if($query->num_rows){
$query = $mysqli->query("SELECT pass FROM user WHERE pass ='{$_GET['pass']}' LIMIT 1;");
if($query->num_rows){
$data['msg']="Logged IN!";
$query = $mysqli->query("SELECT id_user FROM user WHERE login='{$_GET['login']}' LIMIT 1;");
$data['data'][]=$query->fetch_assoc();
exit(json_encode($data));
}else{
$data['err']=1;
$data['msg']="Wrong login credentials.";
exit(json_encode($data));
}
}else{
$data['err']=1;
$data['msg']="This login doesn't exist.";
exit(json_encode($data));
}
}
}else{
$data['err']=1;
$data['msg']="Wrong login credentials";
exit(json_encode($data));
}
I have created there small dictionary $data for my app. I used its err key as a flag to know if any error appeared, msg to inform user about operation results and data to send JSON objects.
Thing you would want to do with if(response == true) if it had exist is similar to construction i used in my onPostExecute(Void w) method in AsyncTask:
if(json.getInt("err")==1){
//something went wrong
}else{
//everything is okay, get JSON, inform user, start new Activity
}
Also here is the way I used $data['data'] to get JSON response:
if($query->num_rows){
while($res=$query->fetch_assoc()){
$data['data'][]=$res;
}
exit(json_encode($data));
}
I am getting a server side json response to load my menu, I tried twice and it gave this error message (the Error parsing data org.json.JSONException).
the reason for that is I'm getting the response partially, in both attempts i got different responses as shown in the images. i think I'm not getting the complete json response, getting only partial response. what should I do to get the complete response.
this is my code
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
try {
path = "http://xxxxxxxxxxxxxxxxxxx";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("CetegoryCode"), "P");
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
this is the image
If your response is returning JsonArray thn need to set tht response string jsonarray. create instance of jsonarray and fill it up with the response.
if its normal get ws thn you can append parameters in url like query string
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
try {
// Append parameters with values eg ?CetegoryCode=p
String path = "http://xxxxxxxxxxxxxxxxxxx?CetegoryCode=p";
URL url = new URL(path);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "");
}
Content = sb.toString();
JSONArray jArray = new JSONArray(Content);
if (jArray != null)
Log.e("Data", "" + jArray.length());
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
}
catch (Exception ex) {
}
}
/*****************************************************/
return null;
}
Try out below code to parse and get JSON response:
public static JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
URL url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
json = convertStreamToString(stream);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
Use getJSONFromUrl method as below in your code:
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
try {
responseJson = new JSONObject(response);
responseJson =getJSONFromUrl("http://xxxxxxxxxxxxxxxxxxx?CetegoryCode=p");
}catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
I am using KSOAP2 to call a Axis 2 webservice from android application,and the response from the web service is in the following format:
[Book{id=1; name=C++ for Begginers; Author=Martin;},Book{id=2; name=Java Development; Author=Charles;},Book{id=3; name=Android Guide; Author=Sam};]
The code for Axis 2 Web service class is as following:
public class Book_Web_Service {
private String url;
private Connection con;
private Statement stmt;
public void connectToDB() {
url = "jdbc:mysql://localhost:3306/book";
try {
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection(url, "root", "");
} catch (Exception e) {
System.out.println("Error - Unable to Connect to the Database" + e);
}
}
public ArrayList<Book> getBooksData() {
ArrayList<Book> booklist = new ArrayList<Book>();
connectToDB();
try {
stmt = (Statement) con.createStatement();
String query ="SELECT * from book ";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Book b = new Book();
b.setId(rs.getString("id"));
b.setName(rs.getString("name"));
b.setAuthor(rs.getString("author"));
booklist.add(b);
}
}
catch (SQLException e) {
System.out.println("Error - Unable to get books data ......" + e);
}
return booklist;
}
}
The code for getting response in android is this:
ArrayList<Book> booklist = new ArrayList<Book>();
METHOD_NAME = "getBooksData";
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
Object result = envelope.getResponse();
// SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
String response = result.toString();
((TextView) findViewById(R.id.booktxt)).setText("Response:"+ response);
} catch (Exception E) {
E.printStackTrace();
((TextView) findViewById(R.id.booktxt)).setText("ERROR:"
+ E.getClass().getName() + ":" + E.getMessage());
}
I want the response again be in arraylist. So that I can show it in list view. But I am not getting it. Is there any android library which can do this or any easy way to do it????
I have a following functionality: I create through the user form a new user. After i had submitted the entered data, created user get the bar-code, which would be used for get access to the other system section by scanning that bar-code with hand-scanner. So how can i get any value (in my case that bar-code from json calls (Post, Get, JSON) with Selenium WebDriver on Java?
Selenium has nothing to do with json. You can use Apache HttpClient library for sending GET, POST, PUT and DELETE requests and receiving the responses. Given below is a simplified function for all cases.
public static HttpResponse sendRequest(String requestType, String body,String url,
String... headers) throws Exception {
try {
HttpGet getRequest = null;
HttpPost postRequest;
HttpPut putRequest;
HttpDelete delRequest;
HttpResponse response = null;
HttpClient client = new DefaultHttpClient();
// Collecting Headers
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String arg : headers) {
//Considering that you are applying header name and values in String format like this "Header1,Value1"
nvps.add(new BasicNameValuePair(arg.split(",")[0], arg
.split(",")[1]));
}
System.out.println("Total Headers Supplied " + nvps.size());
if (requestType.equalsIgnoreCase("GET")) {
getRequest = new HttpGet(url);
for (NameValuePair h : nvps) {
getRequest.addHeader(h.getName(), h.getValue());
}
response = client.execute(getRequest);
}
if (requestType.equalsIgnoreCase("POST")) {
postRequest = new HttpPost(url);
for (NameValuePair h : nvps) {
postRequest.addHeader(h.getName(), h.getValue());
}
StringEntity requestEntity = new StringEntity(body,"UTF-8");
postRequest.setEntity(requestEntity);
response = client.execute(postRequest);
}
if (requestType.equalsIgnoreCase("PUT")) {
putRequest = new HttpPut(url);
for (NameValuePair h : nvps) {
putRequest.addHeader(h.getName(), h.getValue());
}
StringEntity requestEntity = new StringEntity(body,"UTF-8");
putRequest.setEntity(requestEntity);
response = client.execute(putRequest);
}
if (requestType.equalsIgnoreCase("DELETE")) {
delRequest = new HttpDelete(url);
for (NameValuePair h : nvps) {
delRequest.addHeader(h.getName(), h.getValue());
}
response = client.execute(delRequest);
}
return response;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
Selenium only deals with browsers.
Java has classes that do http requests.
see the code below:
private HttpURLConnection setODataConnection(String url, String method) {
try {
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod(method);
// add request header
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json;odata=verbose");
return conn;
} catch (Exception e) {
Assert.fail(e.getMessage());
return null;
}
}
private StringBuilder sendODataRequest(HttpURLConnection conn) {
try {
int responseCode = conn.getResponseCode();
String method = conn.getRequestMethod();
System.out.println("\nSending '" + method + "' request to URL : " + conn.getURL());
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response;
} catch (Exception e) {
Assert.fail(e.getMessage());
return null;
}
}
private ArrayList<String> getByFullUrl(String fullUrl, String entity) {
HttpURLConnection conn = setODataConnection(fullUrl, "GET");
StringBuilder response = sendODataRequest(conn);
ArrayList<String> s = new ArrayList<String>();
Pattern p = Pattern.compile(entity + "\" : (.*?)\\}");
Matcher m = p.matcher(response);
while (m.find()) {
s.add(m.group(1).replace("\"", ""));
}
return s;
}
public ArrayList<String> get(String table, String entity) {
String url = oDataUrl + table + "?$select=" + entity;
return getByFullUrl(url, entity);
}
public void post(String table, String bodyDetails) {
String url = oDataUrl + table;
HttpURLConnection conn = setODataConnection(url, "POST");
conn.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes("details={" + bodyDetails + "}");
wr.flush();
wr.close();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
sendODataRequest(conn);
}
public void put(String table, String id, String bodyDetails) {
String url = oDataUrl + table + "(" + id + ")";
HttpURLConnection conn = setODataConnection(url, "PUT");
conn.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes("details={" + bodyDetails + "}");
wr.flush();
wr.close();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
sendODataRequest(conn);
}