I am doing a simple application in android. The android application has a simple form and when I click the submit button from Android client the form values goes to servlet. Now I have a problem getting string values from servlet to Android client.
How can I send a string data from servlet? And how can I receive string data in Android client?
You need to make a URLConnection to your servlet page and do it. Example for it: http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device
Save the code below as CustomHttpClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* #param url The web address to post the request to
* #param postParameters The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Now add the code where you want to make the client server communication
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",str2));
//here we are passing a variable str2 to the server.
String response = null;
try {
//address should be the http address of the server side code.
response = CustomHttpClient.executeHttpPost("http://www.xxx.xx/xxx.java", postParameters);
String res=response.toString();
res= res.replaceAll("\\s+","");
//res will be the string that you get from the server.
Related
I have a rest webservice java class implemented in a project called pmtv2, and i want to call it from an other class in an other project called sigac as you can see in the picture.
here it is the WService class included in a package in pmtv2
package cat.diba.jee.pmtv2.ws.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cat.diba.jee.pmtv2.ws.rest.manager.RealitzarExpedientManager;
import cat.diba.jee.pmtv2.ws.rest.manager.RealitzarTramitManager;
import cat.diba.jee.pmtv2.ws.rest.message.RestMessage;
import cat.diba.jee.pmtv2.ws.rest.object.RespostaExpedient;
import cat.diba.jee.pmtv2.ws.rest.object.RespostaRealitzarTramit;
import cat.diba.jee.pmtv2.ws.rest.utils.TokenUtils;
/**
* The Class PmtRestWsService.
*/
#Path("/tramitacio")
public class PmtRestWsService {
/**
* The Constant CLASS_ID.
*/
private static final String CLASS_ID = PmtRestWsService.class.getName();
/**
* Log de la classe.
*/
private static final Log LOG = LogFactory.getLog(CLASS_ID);
/**
* The Constant PARAM_SESSION.
*/
private static final String PARAM_SESSION = "session";
/**
* The Constant PARAM_TOKEN.
*/
private static final String PARAM_TOKEN = "token";
/**
* The Constant PARAM_USERNAME.
*/
private static final String PARAM_USERNAME = "username";
/**
* The Constant PARAM_TRAMITS.
*/
private static final String PARAM_TRAMITS = "tramits";
/**
* The constants PARAM_EXPEDIENTS
*/
private static final String PARAM_EXPEDIENTS = "expedients";
/**
* Realitzar tramit.
*
* #param params the params
* #return the pmt expedient
*/
#POST
#Path("/realitzarTramit")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json,application/xml")
public RespostaRealitzarTramit realitzarTramit(String params) {
LOG.debug("Parametres = " + params);
RealitzarTramitManager manager = new RealitzarTramitManager();
RespostaRealitzarTramit resposta = new RespostaRealitzarTramit();
JSONObject jsonObject = new JSONObject(params);
try {
if (validarParametresEntrada(jsonObject)) {
String session = jsonObject.getString(PARAM_SESSION);
String token = jsonObject.getString(PARAM_TOKEN);
if (TokenUtils.validarToken(session, token)) {
resposta = manager.realitzarTramits(jsonObject, jsonObject.getString(PARAM_USERNAME));
} else {
//Token no validat
resposta.setTramitOK(false);
resposta.setError(RestMessage.ERROR_TOKEN_INVALID.getMessage());
}
} else {
//Paràmetres invàlids
resposta.setTramitOK(false);
resposta.setError(RestMessage.ERROR_REALITZAR_TRAMIT_PARAMETRES_ENTRADA.getMessage());
}
} catch (Exception e) {
// Errors als paràmetres d'entrada
LOG.error("ERROR : " + e.getMessage() + " - ORIGEN : " + e.getStackTrace()[0]);
resposta.setTramitOK(false);
resposta.setError(RestMessage.ERROR_REALITZAR_TRAMIT_NO_CONTROLAT.getMessage());
return resposta;
}
return resposta;
}
/**
* Realitzar tramit.
*
* #param params the params
* #return the pmt expedient
*/
#POST
#Path("/expedient")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json,application/xml")
public RespostaExpedient realitzarExpedient(String params) {
LOG.debug("Parametres = " + params);
RealitzarExpedientManager manager = new RealitzarExpedientManager();
RespostaExpedient resposta = new RespostaExpedient();
JSONObject jsonObject = new JSONObject(params);
try {
if (validarParametresEntradaExpedient(jsonObject)) {
String session = jsonObject.getString(PARAM_SESSION);
String token = jsonObject.getString(PARAM_TOKEN);
if (TokenUtils.validarToken(session, token)) {
resposta = manager.realitzarExpedients(jsonObject, jsonObject.getString(PARAM_USERNAME));
} else {
//Token no validat
resposta.setExpedientOK(false);
resposta.setCodiError(901);
resposta.setError(RestMessage.ERROR_TOKEN_INVALID.getMessage());
}
} else {
//Paràmetres invàlids
resposta.setExpedientOK(false);
resposta.setCodiError(902);
resposta.setError(RestMessage.ERROR_REALITZAR_EXPEDIENT_PARAMETRES_ENTRADA.getMessage());
}
} catch (Exception e) {
// Errors als paràmetres d'entrada
LOG.error("ERROR : " + e.getMessage() + " - ORIGEN : " + e.getStackTrace()[0]);
resposta.setExpedientOK(false);
resposta.setCodiError(998);
resposta.setError(RestMessage.ERROR_REALITZAR_EXPEDIENT_NO_CONTROLAT.getMessage());
return resposta;
}
return resposta;
}
/**
* validacio de entrada de expedients
*
* #param jsonObject
* #return
*/
private boolean validarParametresEntradaExpedient(JSONObject jsonObject) {
LOG.debug("validarPeticio(jsonObject) - Inici");
boolean result = true;
try {
jsonObject.getJSONArray(PARAM_EXPEDIENTS);
jsonObject.getString(PARAM_USERNAME);
jsonObject.getString(PARAM_SESSION);
jsonObject.getString(PARAM_TOKEN);
} catch (Exception e) {
result = false;
}
LOG.debug("validarParametresEntrada(jsonObject) - Fi");
return result;
}
/**
* Validar parametres entrada.
*
* #param jsonObject the json object
* #return true, if successful
*/
private boolean validarParametresEntrada(final JSONObject jsonObject) {
LOG.debug("validarPeticio(jsonObject) - Inici");
boolean result = true;
try {
jsonObject.getJSONArray(PARAM_TRAMITS);
jsonObject.getString(PARAM_USERNAME);
jsonObject.getString(PARAM_SESSION);
jsonObject.getString(PARAM_TOKEN);
} catch (Exception e) {
result = false;
}
LOG.debug("validarParametresEntrada(jsonObject) - Fi");
return result;
}
}
is there any way to do it ??
JAX-RS Client API
You can try the JAX-RS Client API, which provides a high-level API for accessing any REST resources. The Client API is defined in the javax.ws.rs.client package.
To access a REST resource using the Client API, you need the following steps:
Obtain an instance of the javax.ws.rs.client.Client interface.
Configure the Client instance with a target.
Create a request based on the target.
Invoke the request.
Example
Try the following to access your webservice (just change the URI paths according to your needs):
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080")
.path("pmtv2")
.path("api")
.path("tramitacio")
.path("realitzarTramit");
RespostaExpedient response = target.request(MediaType.APPLICATION_JSON)
.post(Entity.json(data)), RespostaExpedient.class);
More information
You will need an implementation of the JAX-RS Client API, such as Jersey or RESTEasy.
you should have an application server, you can use tomcat on localhost, and from the other project you just send à Request on your rest url : localhost[portNumber]/[yourRestService]
you can see this : How to send HTTP request in java?
You can do a http getrequest to your webservice with required paramters. For that you will need to add httpclient jar in your project.
For httpget request to work you must deploy your webservice on application server like tomcat or jboss or glassfish.
//Creating http client
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("localhost:8080/pmtv2/tramitacio/realitzarTramit?params="+params); // call to your webservice with required parameters
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
//receiving response
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
Publish the aplication in an aplication server (Tomcat?), obtain a URL where it is published and use some code like this to call it:
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
URL url = new URL(desturl);
huc.setRequestMethod("GET");
byte[] postData = null;
int postDataLength;
huc.setDoOutput(true);
postData = data.getBytes( StandardCharsets.UTF_8 );
postDataLength = postData.length;
huc.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
huc.setRequestProperty( "charset", "utf-8");
huc.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
huc.connect();
rd = new BufferedReader(new InputStreamReader(huc.getInputStream()));
retcode = huc.getResponseCode();
I'm new to Android and Java. I'm creating an app to login to my ISP. This is the page: http://reliancebroadband.co.in/reliance/login.do
Earlier, I was using a python script, which worked flawlessly. Its like this:
#!/usr/bin/env python
# encoding: utf-8
import urllib2, urllib, cookielib
username = 'my-username'
password = 'my-password'
jar = cookielib.FileCookieJar("cookies")
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
response = opener.open("http://reliancebroadband.co.in/reliance/startportal_isg.do")
login_data = urllib.urlencode({'userId' : username, 'password' : password, 'action' : 'doLoginSubmit'})
resp = opener.open('http://reliancebroadband.co.in/reliance/login.do', login_data)
And now i'm trying to create an android app(source: http://www.compiletimeerror.com/2013/01/login-application-for-android.html#.U7AFBPmSz9Y) (Tried contacting the developer there, but he's not responding.)
The app is compiling correctly, but while tring to login, its just returning the source code of the login page in the error dialogue, instead of logging in.
Here's the code:
MainActivity.java:
package com.app.reliancebblogin;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressLint("NewApi")
public class MainActivity extends Activity
{
EditText un, pw;
TextView error;
Button ok;
private String resp;
private String errorMsg;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
un = (EditText) findViewById(R.id.et_un);
pw = (EditText) findViewById(R.id.et_pw);
ok = (Button) findViewById(R.id.btn_login);
error = (TextView) findViewById(R.id.tv_error);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
/** According with the new StrictGuard policy, running long tasks on the Main UI thread is not possible
So creating new thread to create and execute http operations */
new Thread(new Runnable()
{
#Override
public void run()
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",un.getText().toString()));
postParameters.add(new BasicNameValuePair("password",pw.getText().toString()));
String response = null;
try
{
response = SimpleHttpClient.executeHttpPost("http://reliancebroadband.co.in/reliance/login.do", postParameters);
String res = response.toString();
resp = res.replaceAll("\\s+", "");
}
catch (Exception e)
{
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try
{
/** wait a second to get response from server */
Thread.sleep(1000);
/** Inside the new thread we cannot update the main thread
So updating the main thread outside the new thread */
error.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty())
{
error.setText(errorMsg);
}
}
catch (Exception e)
{
error.setText(e.getMessage());
}
}
});
}
}
SimpleHttpClient.java:
package com.app.reliancebblogin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class SimpleHttpClient
{
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient()
{
if (mHttpClient == null)
{
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* #param url The web address to post the request to
* #param postParameters The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
So as i said i'm bouncing back and forth between these two errors when trying to run HttpClient.execute(HttpPost). Getting IllegalStateException
public class NetMethods {
private static HttpClient client = new DefaultHttpClient();
public static void getStuff() {
ArrayList<Alarm> alarms = new ArrayList<Alarm>();
HttpPost post = HttpPostFactory.getHttpPost("GetStuff");
StringBuilder builder = new StringBuilder();
HttpResponse response = client.execute(post); // Exception thrown here
...
Also, my MttpPostFactory just has this
import org.apache.http.client.methods.HttpPost;
public class HttpPostFactory {
private static final String url = "http://example.com/ExampleFolder/";
public static HttpPost getHttpPost(String s) {
return new HttpPost(url + s);
}
}
This may arise from not closing the InputStream's you get from HttpClient, especially if arising from different threads...either not reading the whole content or calling the same HttpClient instance from two different threads.
I found solution from Androider's blog:
I got the log :
Invalid use of SingleClientConnManager: connection still allocated.
or
Caused by: java.lang.IllegalStateException: No wrapped connection.
or
Caused by: java.lang.IllegalStateException: Adapter is detached.
Finally got Solution:
public static DefaultHttpClient getThreadSafeClient() {
DefaultHttpClient client = new DefaultHttpClient();
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);
return client;
}
Try with this..
// Execute the asynctask with your URL
new myAsyncTask().execute("http://example.com/ExampleFolder/");
// Asynctask Callback method
private class myAsyncTask extends AsyncTask<String, Void, Void>
{
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(String... arg0)
{
// Creating service handler class instance
ServiceHandler serhand = new ServiceHandler();
// Making a request to url and getting response
serhand.makeServiceCall(arg0[0], ServiceHandler.GET);
return null;
}
protected void onPostExecute(Void result)
{
}
}
// Service Handler class
package yourpagename
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
I am trying to call another class called HttpUtilityTester.java from Mainactivity.java.
Actually I'd like to test HttpUtility.sendPostRequest from HttpUtility.java with a click on a button.
The spot is marked with this comment: "//here I need help from stackoverflow"
This is already added to my button in the activity_main.xml:
android:onClick="sendMessage1"
here is Mainactivity.java:
package com.example.mythirdapp;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
//here I need help from stackoverflow
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
here is HttpUtility.java:
package com.example.mythirdapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class HttpUtility {
/**
* Represents an HTTP connection
*/
private static HttpURLConnection httpConn;
/**
* Makes an HTTP request using GET method to the specified URL.
*
* #param requestURL
* the URL of the remote server
* #return An HttpURLConnection object
* #throws IOException
* thrown if any I/O error occurred
*/
public static HttpURLConnection sendGetRequest(String requestURL)
throws IOException {
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoInput(true); // true if we want to read server's response
httpConn.setDoOutput(false); // false indicates this is a GET request
return httpConn;
}
/**
* Makes an HTTP request using POST method to the specified URL.
*
* #param requestURL
* the URL of the remote server
* #param params
* A map containing POST data in form of key-value pairs
* #return An HttpURLConnection object
* #throws IOException
* thrown if any I/O error occurred
*/
public static HttpURLConnection sendPostRequest(String requestURL,
Map<String, String> params) throws IOException {
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoInput(true); // true indicates the server returns response
StringBuffer requestParams = new StringBuffer();
if (params != null && params.size() > 0) {
httpConn.setDoOutput(true); // true indicates POST request
// creates the params string, encode them using URLEncoder
Iterator<String> paramIterator = params.keySet().iterator();
while (paramIterator.hasNext()) {
String key = paramIterator.next();
String value = params.get(key);
requestParams.append(URLEncoder.encode(key, "UTF-8"));
requestParams.append("=").append(
URLEncoder.encode(value, "UTF-8"));
requestParams.append("&");
}
// sends POST data
OutputStreamWriter writer = new OutputStreamWriter(
httpConn.getOutputStream());
writer.write(requestParams.toString());
writer.flush();
}
return httpConn;
}
/**
* Returns only one line from the server's response. This method should be
* used if the server returns only a single line of String.
*
* #return a String of the server's response
* #throws IOException
* thrown if any I/O error occurred
*/
public static String readSingleLineRespone() throws IOException {
InputStream inputStream = null;
if (httpConn != null) {
inputStream = httpConn.getInputStream();
} else {
throw new IOException("Connection is not established.");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String response = reader.readLine();
reader.close();
return response;
}
/**
* Returns an array of lines from the server's response. This method should
* be used if the server returns multiple lines of String.
*
* #return an array of Strings of the server's response
* #throws IOException
* thrown if any I/O error occurred
*/
public static String[] readMultipleLinesRespone() throws IOException {
InputStream inputStream = null;
if (httpConn != null) {
inputStream = httpConn.getInputStream();
} else {
throw new IOException("Connection is not established.");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
List<String> response = new ArrayList<String>();
String line = "";
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
return (String[]) response.toArray(new String[0]);
}
/**
* Closes the connection if opened
*/
public static void disconnect() {
if (httpConn != null) {
httpConn.disconnect();
}
}
}
here is HttpUtilityTester.java:
package com.example.mythirdapp;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class HttpUtilityTester {public static void main(String[] args) {
// test sending GET request
String requestURL = "http://www.google.com";
try {
HttpUtility.sendGetRequest(requestURL);
String[] response = HttpUtility.readMultipleLinesRespone();
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
HttpUtility.disconnect();
System.out.println("=====================================");
// test sending POST request
Map<String, String> params = new HashMap<String, String>();
requestURL = "https://accounts.google.com/ServiceLoginAuth";
params.put("Email", "your_email");
params.put("Passwd", "your_password");
try {
HttpUtility.sendPostRequest(requestURL, params);
String[] response = HttpUtility.readMultipleLinesRespone();
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
HttpUtility.disconnect();
}
}
I tried to add code of the HttpUtilityTester.java to my Mainactivity.java like this:
...public class MainActivity extends Activity {
public void sendMessage1(View v){
// test sending POST request
Map<String, String> params = new HashMap<String, String>();
requestURL = "https://accounts.google.com/ServiceLoginAuth";
params.put("Email", "your_email");
params.put("Passwd", "your_password");
try {
HttpUtility.sendPostRequest(requestURL, params);
String[] response = HttpUtility.readMultipleLinesRespone();
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
HttpUtility.disconnect();
}...
But logcat sais: "could not execute method of the activity"
The following will be called when you click that button, so place it in your code where applicable.
public void sendMessage1(View v){
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm working on an Android app that has to store data in a database.
This database also has to be accessed by an iPhone app and a web application.
I would like to use Mysql for this, because it's open source.
I was looking for some information on this and apparently I need to make a webservice
that connects to a database. Probably in php, but I don't have any experience with php...
How do I write this webservice and where do I store it? Where do I make and store the database? ...
Can anyone help me on this issue?
tnx
Use SQL server to manage the data on your desktop and create a web-service in .Net on Visual Studio.
Then connect to the web-service in your application and set/get data from the DB.
Link on how to make a web-service in .NET (does not include the implementation in Android) : http://srikanthtechnologies.com/blog/dotnet/wsdaljava.aspx
Links on how to connect your service with Android : http://seesharpgears.blogspot.in/2010/11/basic-ksoap-android-tutorial.html
http://www.codeproject.com/Articles/304302/Calling-Asp-Net-Webservice-ASMX-From-an-Android-Ap
http://adrianandroid.blogspot.in/2012/05/access-c-net-web-service-in.html
My Custom Class that will contact the localhost Server(WAMP or XAMP Server)
CustomHttpClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/*
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/*
* Performs an HTTP Post request to the specified url with the specified
* parameters.
*
* #param url The web address to post the request to
*
* #param postParameters The parameters to send via the request
*
* #return The result of the request
*
* #throws Exception
*/
public static String executeHttpPost(String url,
ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpPost request = new HttpPost("http://192.168.1.38/" +url (pathoffilenameyouarecalling));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url
* The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class calling this will implement like this way.
ArrayList<NameValuePair> postParameter = new ArrayList<NameValuePair>();
postParameter.add(new BasicNameValuePair("parametertobesent",value));
respons = CustomHttpClient.executeHttpPost("urlofservice",postParameter);
The php files should be present in the htdocs of the XAMP Server