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????
Related
I have developed an Android Application which consumes a Webservice. I have tested the application on different devices and its working perfectly but on the tablet of my client, it's throwing an exception. All devices on which application is tested are running Android 6.0.1 Marshmallow.Following is the exception
java.net.ConnectException: failed to connect to web.abc.com(port 80):connect failed: ECONNREFUSED (Connection refused)
Following is my code for consuming Webservice
String namespace = "http://web.abc.com/";
private static final String url = "http://web.abc.com/WebService/ServiceFileName.asmx";
String SOAP_ACTION;
SoapObject request = null, objMessages = null;
SoapSerializationEnvelope envelope;
HttpTransportSE androidHttpTransport;
/**
* Set Envelope
*/
protected void SetEnvelope() {
try {
// Creating SOAP envelope
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//You can comment that line if your web service is not .NET one.
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
//envelope.addMapping(namespace, "ProductStausResponse",new ProductStausResponse().getClass());
androidHttpTransport = new HttpTransportSE(url);
androidHttpTransport.debug = true;
} catch (Exception e) {
e.printStackTrace();
Log.v("Soap Exception", e.toString());
System.out.println("Soap Exception---->>>" + e.toString());
}
}
// MethodName variable is define for which webservice function will call
public String getProductStatus(String MethodName, String Parameter)
{
try {
ProductCode = ProductCode.trim();
SOAP_ACTION = namespace + MethodName;
//Adding values to request object
request = new SoapObject(namespace, MethodName);
/// Code for setting properties
SetEnvelope();
try {
//SOAP calling webservice
androidHttpTransport.call(SOAP_ACTION, envelope);
//Got Webservice response
String result = envelope.getResponse().toString();
return result;
} catch (Exception e) {
// TODO: handle exception
//e.printStackTrace();
//return "Exception";
return e.toString();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.v("Soap Exception", e.toString());
//return "Exception";
return e.toString();
}
}
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 am fairly new to android programming and I have faced a small problem. I have an arraylist consisting of names of person selected from a multi-select listview, the problem is that Whenever I insert those arraylist values into the database, It inserts it as one string:
Database row. How do i iterate thru an arraylist and at the same time insert its values into the database?
here is my code:
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "CONNECTION FAIL", Toast.LENGTH_LONG).show();
} else {
String samp = "";
String names = "";
samp = myArrayAdapter.getCheckedItems().toString();
ArrayList<String> data1 = new ArrayList<String>();
data1.add(samp);
for(int x=0; x<data1.size(); x++)
{
names += String.valueOf(data1.get(x));
String query = "INSERT INTO AUTOINC(PersonName)"+"VALUES('"+names+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
}
Toast.makeText(getApplicationContext(), "INSERT SUCCESS", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "INSERT FAILED", Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception", ex);
}
Thank you for any future replies.
Can you try with that?
List<String> data1 = new ArrayList<String>(Arrays.asList(samp.replace("[","").replace("]","").split(",")));
for (String name : data1) {
names += name; // This lines concatenate the name.
//If you want to insert single name the you can directly insert the name value into databas.
String query = "INSERT INTO AUTOINC(PersonName)"+"VALUES('"+name+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
}
look at this code...
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi=new PropertyInfo();
pi.setName("UserName");
pi.setValue(txtName.getText().toString());
pi.setType(String.class);
request.addProperty(pi);
pi=new PropertyInfo();
pi.setName("UserAge");
pi.setValue(txtVal.getText().toString());
pi.setType(String.class);
request.addProperty(pi);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(webRequest);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope);
Log.d("CheckLogin-SOAP ACTION", SOAP_ACTION + METHOD_NAME);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
Log.d("CheckLogin - Response", response.toString());
status= Boolean.valueOf(response.toString());
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
I made servlet for storing file from html..
Is it possible to use that servlet to save my file from android code..
my servlet follows
public class UploadImage extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
System.out.println("request: "+request);
if (!isMultipart) {
System.out.println("File Not Uploaded");
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
System.out.println("items: "+items);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()){
String name = item.getFieldName();
System.out.println("name: "+name);
String value = item.getString();
System.out.println("value: "+value);
} else {
try {
String itemName = item.getName();
Random generator = new Random();
int r = Math.abs(generator.nextInt());
String reg = "[.*]";
String replacingtext = "";
System.out.println("Text before replacing is:-" + itemName);
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(itemName);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, replacingtext);
}
int IndexOf = itemName.indexOf(".");
String domainName = itemName.substring(IndexOf);
System.out.println("domainName: "+domainName);
String finalimage = buffer.toString()+"_"+r+domainName;
finalimage=finalimage.substring(finalimage.lastIndexOf("\\")+1,finalimage.length());
System.out.println("Final Image==="+finalimage);
File savedFile = new File(finalimage);
item.write(savedFile);
FileInputStream in=new FileInputStream(savedFile);
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String driver = "com.mysql.jdbc.Driver";
String username = "root";
String userPassword = "admin";
String strQuery = null;
String strQuery1 = null;
String imgLen="";
try {
System.out.println("itemName::::: "+itemName);
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,username,userPassword);
PreparedStatement stmt=conn.prepareStatement("insert into testimage(image) values(?)");
stmt.setBinaryStream(1,in,in.available()+2);
stmt.executeUpdate();
stmt.close();
System.out.println("Query Executed Successfully++++++++++++++");
out.println("image inserted successfully");
out.println("</body>");
out.println("</html>");
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
i have idea such some thing like this..but not sure.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
what the jar or to do this task
your's reply is very helpful to me..
you can use apache Http Components and mime4j to send multipart to your servlet
see this example
InputStream inputStream = this.getAssets().open("image.png");
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("http://10.10.10.144:8080/TestingApacheHttpClients/PostGetServletTest");
byte[] data = IOUtils.toByteArray(inputStream);//from apache commons IO
InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data), "uploadedFile");
StringBody sb1 = new StringBody("Nammaeri 101");
StringBody sb2 = new StringBody("this is tamara");
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("fileUploaded", isb);
multipartEntity.addPart("parmaeter1", sb1);
multipartEntity.addPart("parameter2", sb2);
request.setEntity(multipartEntity);
HttpResponse response = client.execute(request);
customhttpclient.java is available at this link customhttpclient.java
Use this in your project and then access from the servlet in the following manner
ArrayList<NameValuePair> postdates = new ArrayList<NameValuePair>();
postdates.add(new BasicNameValuePair("accountno",selected_accountno));
postdates.add(new BasicNameValuePair("fromdate", fromdate));
postdates.add(new BasicNameValuePair("todate", todate));
try {
String response = CustomHttpClient.executeHttpPost("http://"+server_ip+":8080/AndroidResponse/ICICIGetAccountStatement", postdates);
resp = response.toString();
resp = resp.replaceAll("\\s+","");
//System.out.println("Resp from Server: "+ resp);
} catch (Exception e) {
//System.out.println("Error at after server response :"+e.toString());
}