´
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");
Related
I am trying to learn how to connect to an API and receieve and parse JSON data so I am currently following an example on this webpage: http://www.whycouch.com/2012/12/how-to-create-android-client-for-reddit.html, but I am getting an error that says:
E/fetchPosts(): org.json.JSONException: End of input at character 0 of
My app is connecting because it says that a new host connection has been established so I'm not quite sure as to why it's getting a blank response. Below is my class that gets the connection and reads the contents. If I had to guess where I went wrong, I would say it has to do with the request properties, but I went to reddit's website and formatted it like they want and it's still not returning anything. Thank you.
public class RemoteData {
/*
This method returns a connection to the specified URL,
with necessary properties like timeout and user-agent
set to your requirements.
*/
public static HttpURLConnection getConnection(String url){
System.out.println("URL: " + url);
HttpURLConnection hcon = null;
try{
hcon = (HttpURLConnection)new URL(url).openConnection();
hcon.setReadTimeout(30000); //Timeout set at 30 seconds
hcon.setRequestProperty("User-Agent", "android:com.example.reddittestappbydrew:v0.0.1");
}catch(MalformedURLException e){
Log.e("getConnection()", "Invalid URL: " +e.toString());
}catch (IOException e){
Log.e("getConnection()", "Could not connect: " + e.toString());
}
return hcon;
}
/*
A utility method that reads the contents of a url and returns them as a string
*/
public static String readContents(String url){
HttpURLConnection hcon = getConnection(url);
if(hcon == null) return null;
try{
StringBuffer sb = new StringBuffer(8192);
String tmp = "";
BufferedReader br = new BufferedReader(new InputStreamReader(hcon.getInputStream()));
while((tmp = br.readLine()) != null){
sb.append(tmp).append("\n");
}
br.close();
return sb.toString();
}catch(IOException e){
Log.d("READ FAILED", e.toString());
return null;
}
}
}
The code you have written looks pretty naive for getting html/json response data from my URL as redirects are not being handled there. Either you handle redirects in your code which you can do by checking hcon.getResponseCode() whose value should be 200 for you to read the data successfully. In case it is not 200 and something else like 301 (redirects) or 403 (authorization required), you need to handle these responses accordingly.
Here I am giving you a simple code which uses HttpClient (I am using httpclient-4.2.1) library from apache, and gets the response back as String.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.fileupload.util.Streams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpUtils {
private static Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);
public static String getResponse(String url) throws IOException {
return getResponse(url, "UTF-8");
}
public static String getResponse(String url, String characterEncoding) throws IOException {
return getByteArrayOutputStream(url).toString(characterEncoding);
}
public static byte[] getBytes(String url) throws IOException {
return getByteArrayOutputStream(url).toByteArray();
}
public static ByteArrayOutputStream getByteArrayOutputStream(String url) throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpclient.execute(httpGet);
LOGGER.debug("Status Line: " + response.getStatusLine());
HttpEntity resEntity = response.getEntity();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Streams.copy(resEntity.getContent(), byteArrayOutputStream, true);
return byteArrayOutputStream;
}
public static void main(String[] args) throws IOException {
System.out.println(getResponse("https://www.reddit.com/r/AskReddit/.json"));
}
}
Use this code to achieve what you want and in case you don't want to use HTTPClient API, then modify your existing code to handle http status codes but it would be simple for you to use above code.
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 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){
}
I've followed the UA tutorials and got my APID , and successfully recieved test push message on my android device.
Now the next thing that I like to do is to target my device using JAVA and send push messaged.
From what I've seen so far the best way to achieve this is using their web API.
However When I'm trying to send a post message I always get the following error :
java.io.IOException: Server returned HTTP response code: 401 for URL: https://go.urbanairship.com/api/push/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.Sender.Sender.main(Sender.java:56)
This is the code that I use :
package com.Sender;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class Sender {
/**
* #param args
*/
public static void main(String[] args) {
try {
String responseString = "";
String outputString = "";
String username = "MWMoRVhmRXOG6IrvhMm-BA";
String password = "ebsJS2iXR5aMJcOKe4rCcA";
MyAuthenticator ma= new MyAuthenticator(username, password);
Authenticator.setDefault(ma);
URL url = new URL("https://go.urbanairship.com/api/push/");
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConnection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String APID = "23eef280-19c8-40fc-b798-788f50e255a2";
String postdata = "{\"android\": {\"alert\": \"Hello from JAVA!\"}, \"apids\": [\""+APID+"\"]}";
byte[] buffer = new byte[postdata.length()];
buffer = postdata.getBytes("UTF8");
bout.write(buffer);
byte[] b = bout.toByteArray();
httpConn.setRequestProperty("Content-Length",
String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "application/json");
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
InputStreamReader isr = new InputStreamReader(
httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
System.out.println(outputString);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Can you help me please ?
HTTP 401 represent Unauthorized access. In your code even though your created Authenticator, you didn't provide it as part of post request header. Here is tutorial on how to set authenticator for a URLConnection.
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.