call a REST webservice from an other project - java

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();

Related

Method not allowed error (405) Mojang API

´
I am currently working on a project where I am trying to log the player in through the mojang API but it returns an error (405) Method not allowed (seems like it somehow thinks I'm sending a GET request instead of a POST)
Would be glad if anyone could help me out.
Here is the source code for the auth request:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONException;
import org.json.JSONObject;
import net.sxlver.accountchecker.exception.AccessDeniedException;
import net.sxlver.accountchecker.manager.OutputManager;
public class AuthRequest {
private OutputManager outputManager = new OutputManager();
/**
*
* #param username
* #param password
* #return required JSON Object containing the credentials and a few other information the API needs as String
* #throws JSONException if JSONObject contains invalid data
*/
public String MakeJSONRequest(String username, String password) throws JSONException {
JSONObject json1 = new JSONObject();
json1.put("name", "Minecraft");
json1.put("version", "1");
JSONObject json = new JSONObject();
json.put("username", username);
json.put("password", password);
return json.toString();
}
/**
*
* #param url
* #param content
* #return the API's response as String (JSONObject)
* #throws AccessDeniedException if the provided credentials are invalid
* #throws IOException if any issues are encountered whilest preparing and/or sending the request
* #throws JSONException
*/
public boolean httpRequest(URL url, String content) throws AccessDeniedException, IOException, JSONException {
byte[] contentBytes = content.getBytes("UTF-8");
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", Integer.toString(contentBytes.length));
String response = "";
BufferedReader responseStream;
if(((HttpsURLConnection) connection).getResponseCode() == 200) {
responseStream = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
}else {
responseStream = new BufferedReader(new InputStreamReader(((HttpsURLConnection) connection)
.getErrorStream(), "UTF-8"));
}
response = responseStream.readLine();
responseStream.close();
if(((HttpsURLConnection) connection).getResponseCode()!=200) {
JSONObject json = new JSONObject();
try {
json = new JSONObject(content);
} catch (JSONException e) {
System.out.println("Error: Invalid JSON request. Could not parse content to JSONObject.");
return false;
}
outputManager.print("Access denied for " + json.get("username") + ":" + json.get("password")
+ ". Response code: " + ((HttpsURLConnection) connection).getResponseCode());
return false;
}
return true;
}
}
Note: I have already done a lot of debugging and the provided credentials are working and they're not formatted wrong.
Fix: I have added the following lines
OutputStream requestStream = connection.getOutputStream();
requestStream.write(contentBytes, 0, contentBytes.length);
requestStream.close();
Set the request method in HttpURLConnection instance, default value is GET.
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");

Sending Post info to php file (Java)

How can I send Post Values to a PHP File?
So that the PHP File can send this value for example to a databse or something else.
So that I can send a string from my java file to the php file that works with it.
As i answered some time ago, i made a class for this, hope it helps.
However, you should show us what you have tried instead of just asking.
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Vector;
public class SiteFX {
private String postParameters = "";
private String webPage;
private Vector<String>names;
private Vector<String>values;
public SiteFX(){
values = new Vector<String>();
names = new Vector<String>();
}
/**
* Adds a post variable (page.php?name=value)
*
* #param name the variable name
* #param value the variable value, can be set to null, the url will simply become &name instead of &name=value
* null
*/
public void addPostValue(String name, String value) {
if (value == null) {
try {
postParameters += "&" + URLEncoder.encode(name, "UTF-8");
names.add(name);
values.add("");
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
postParameters += "&" + URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
names.add(name);
values.add(value);
}
}
/**
* Send post data without waiting for site output
*
* #return true if sending data terminated succesfully
*/
public boolean sendPost() {
try {
if (webPage == null || webPage.equals("")) {
throw new Exception("Empty url");
}
URL url = new URL(webPage);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(postParameters);
wr.flush();
} catch (Exception e) {
e.printStackTrace();
return false;
}
postParameters = "";
return true;
}
/**
* Sends data, then waits for site output
*
* #return null if no data is received, or a String containing the data
*/
public String sendPostWithReturnValue() {
String returnValue = "";
try {
if (webPage == null || webPage.equals("")) {
throw new Exception("Empty url");
}
URL url = new URL(webPage);
URLConnection conn =
url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr =
new OutputStreamWriter(conn.getOutputStream());
wr.write(postParameters);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
returnValue += line + "\n";
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
postParameters = "";
values = null;
names=null;
values = new Vector<String>();
names = new Vector<String>();
return returnValue;
}
/**
* Sets the page to point at for sending post variables
*
* #param webPageToPointAt the page that will receive your post data
*/
public void setWebPageToPointAt(String webPageToPointAt) {
webPage = webPageToPointAt;
}
/**
* #returns A Nx2 matrix containing all parameters name and values
*/
public String[][] getParameters() {
String[][] str = new String[names.size()][2];
for (int i = 0; i < str.length; i++) {
str[i][0] = names.get(i);
str[i][1] = values.get(i);
}
return str;
}
}

call java class with click on a button

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){
}

How to connect android to a remote database [closed]

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

How to send data from java servlet to android client

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.

Categories

Resources