Can't get String sent to PHP on server from Android - java

I know the apache library is deprecated, but I was wondering if it is possible to send the string "ansi" in this code to a PHP script on a server at a URL. My code is below and I don't know what I'm missing.
Any help would be appreciated.
I've looked up a lot online and many people suggest using StringEntity, which I did, but it's still not working :/
I'm trying to retrieve a lot of data from the PHP but the PHP script needs the string "ansi" before data can be retrieved.
public class HttpServiceClass {
private ArrayList<NameValuePair> params;
private ArrayList<NameValuePair> headers;
private String ansi;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public HttpServiceClass(String url, String ansi) {
this.url = url;
this.ansi = ansi;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value) {
headers.add(new BasicNameValuePair(name, value));
}
public void ExecuteGetRequest() throws Exception {
String combinedParams = "";
if (!params.isEmpty()) {
combinedParams += "?";
for (NameValuePair p : params) {
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), "UTF-8");
if (combinedParams.length() > 1) {
combinedParams += "&" + paramString;
} else {
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
for (NameValuePair h : headers) {
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url, ansi);
}
public void ExecutePostRequest() throws Exception {
HttpPost request = new HttpPost(url);
request.setEntity(new StringEntity(ansi));
for (NameValuePair h : headers) {
request.addHeader(h.getName(), h.getValue());
}
if (!params.isEmpty()) {
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url, ansi);
}
private void executeRequest(HttpUriRequest request, String url, String ansi) {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}

Related

Can not to use httpclient to send httprequest in circulation?

I am try to make a tiny util so that I can send a HttpRequest repeatedly and I use HttpClient to do this.
But I have a problem, I can not send HttpRequest in circulation. To more detail, it can sent request at first cycle, but after that it can not send request and the thread is waiting at there.
there is the main code:
for (int i = 0; i < 10; i++) {
HttpResponse result = Launcher.bulider()
.setCharSet("utf-8")
.setHttpMethod("GET")
.setUrl("http://www.baidu.com")
.fullResponse();
System.out.println(result.getStatusLine().getStatusCode());
}
Launcher.java:
public abstract class Launcher {
public static class bulider{
private String httpMethod;
private String url;
private Map<String, String> params;
private String charSet;
private Class type;
public bulider setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
return this;
}
public bulider setUrl(String url) {
this.url = url;
return this;
}
public bulider setParams(Map<String, String> params) {
this.params = params;
return this;
}
public bulider setCharSet(String charSet) {
this.charSet = charSet;
return this;
}
public String data() {
if (httpMethod.equalsIgnoreCase(HttpMethod.GET)){
return HttpTemplate.doGet(this.url,this.params,this.charSet);
}
if (httpMethod.equalsIgnoreCase(HttpMethod.POST)){
return HttpTemplate.doPost(this.url,this.params,this.charSet);
}
return null;
}
public <T> T jsonObject(Class<T> type) {
if (httpMethod.equalsIgnoreCase(HttpMethod.GET)) {
return HttpTemplate.getReObj(type, this.url, this.params, this.charSet);
}
if (httpMethod.equalsIgnoreCase(HttpMethod.POST)) {
return HttpTemplate.postReObj(type, this.url, this.params, this.charSet);
}
return null;
}
public HttpResponse fullResponse() {
if (httpMethod.equalsIgnoreCase(HttpMethod.GET)) {
return HttpTemplate.getReResponse(this.url, this.params, this.charSet);
}
if (httpMethod.equalsIgnoreCase(HttpMethod.POST)) {
return HttpTemplate.postReResponse(this.url, this.params, this.charSet);
}
return null;
}
}
public static bulider bulider(){
return new bulider();
}
}
HttpTemplate.java:
public class HttpTemplate {
private static final Logger logger = LoggerFactory.getLogger(HttpTemplate.class);
private static final CloseableHttpClient httpClient;
public static final String DEFAULT_CHARSET = "utf-8";
static {
RequestConfig config = RequestConfig.custom().setConnectTimeout(6000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
public static String doGet(String url, Map<String, String> param, String charset) {
try {
HttpGet httpGet = (HttpGet) initRequestParam("Get", url, param, charset);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (!String.valueOf(statusCode).startsWith("2")) {
throw new RuntimeException("Http Template Error :: status code " + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
EntityUtils.consume(entity);
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String doPost(String url, Map<String, String> params, String charset) {
try {
HttpPost httpPost = (HttpPost) initRequestParam("Post", url, params, charset);
HttpResponse response = httpClient.execute(httpPost);
int status = response.getStatusLine().getStatusCode();
if (!String.valueOf(status).startsWith("2")) {
throw new RuntimeException("Http Template Error :: status error " + status);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity);
}
EntityUtils.consume(entity);
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static <T> T getReObj(Class<T> type, String url, Map<String, String> param, String charset) {
try {
HttpGet httpGet = (HttpGet) initRequestParam("Get", url, param, charset);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (!String.valueOf(statusCode).startsWith("2")) {
throw new RuntimeException("Http Template Error :: status code " + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
logger.info(result);
EntityUtils.consume(entity);
T resultNew = JSON.parseObject(result, type);
logger.info(resultNew.getClass().toString());
return resultNew;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static <T> T postReObj(Class<T> type, String url, Map<String, String> params, String charset) {
try {
HttpPost httpPost = (HttpPost) initRequestParam("Post", url, params, charset);
HttpResponse response = httpClient.execute(httpPost);
int status = response.getStatusLine().getStatusCode();
if (!String.valueOf(status).startsWith("2")) {
throw new RuntimeException("Http Template Error :: status error " + status);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
EntityUtils.consume(entity);
T resultNew = JSON.parseObject(result, type);
return resultNew;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static HttpResponse getReResponse(String url, Map<String, String> param, String charset) {
try {
HttpGet httpGet = (HttpGet) initRequestParam("Get", url, param, charset);
return httpClient.execute(httpGet);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static HttpResponse postReResponse(String url, Map<String, String> param, String charset) {
try {
HttpPost httpPost = (HttpPost) initRequestParam("Post", url, param, charset);
return httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static HttpRequestBase initRequestParam(String methodName, String url, Map<String, String> params, String charset) {
logger.info(url);
if (!StringKit.isNotBlank(url)) {
return null;
}
if (null == charset) {
charset = DEFAULT_CHARSET;
}
List<NameValuePair> pairList = null;
if (params != null && !params.isEmpty()) {
pairList = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairList.add(new BasicNameValuePair(entry.getKey(), value));
}
}
}
if ("Get".equalsIgnoreCase(methodName)) {
try {
if (pairList != null) {
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairList, charset));
}
logger.info(url);
HttpGet httpGet = new HttpGet(url);
return httpGet;
} catch (IOException e) {
e.printStackTrace();
}
} else if ("Post".equalsIgnoreCase(methodName)) {
try {
HttpPost httpPost = new HttpPost(url);
if (pairList != null && !pairList.isEmpty()) {
httpPost.setEntity(new UrlEncodedFormEntity(pairList));
}
return httpPost;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>httpLaunch</groupId>
<artifactId>httpLaunch</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--http client-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
there is the whole code:https://github.com/vzardlloo/http-launcher

Is this correct approach to submitting JSON via HTTP POST to a java Web Server?

I construct the JSON Object
JSONObject jsonobj = new JSONObject();
JSONObject geoJsonObj = new JSONObject();
try {
jsonobj.put("action","put-point");
geoJsonObj.put("lng", longitude);
geoJsonObj.put("lat", latitude);
geoJsonObj.put("rangeKey", rangeKey);
geoJsonObj.put("schoolName", "TESTSCHOOL535353");
jsonobj.put("request", geoJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
I Execute an AsyncTask
new HTTPtoServer().execute(jsonobj);
The AsyncTask looks like this:
private class HTTPtoServer extends AsyncTask<JSONObject, Void, String> {
#Override
protected String doInBackground(JSONObject... params) {
//Prepare HTTP Post Client
DefaultHttpClient myClient = new DefaultHttpClient();
HttpPost myPost = new HttpPost(ElasticBeanStalkEndpoint);
StringEntity se = null;
Log.v("TEST","TEST");
try {
se = new StringEntity(params[0].toString());
Log.v("MY SE", se.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
myPost.setEntity(se);
HttpResponse httpresponse = null;
try {
httpresponse = myClient.execute(myPost);
} catch (IOException e) {
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(httpresponse.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
return responseText;
}
#Override
protected void onPostExecute(String s) {
Log.v("MY STRING", s);
}
}
However my JSON Object appears to never be "sending"?
Or maybe it is, but in an incorrect format?
The Java Tomcat server doesn't seem to be doing anything with the data?
My StringEntity results in :
org.apache.http.entity.StringEntity#528111f8
When I do se.toString()... Is this correct?
I seem to be a bit confused.
SERVER CODE:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
try {
StringBuffer buffer = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject jsonObject = new JSONObject(buffer.toString());
PrintWriter out = response.getWriter();
String action = jsonObject.getString("action");
log("action: " + action);
JSONObject requestObject = jsonObject.getJSONObject("request");
log("requestObject: " + requestObject);
if (action.equalsIgnoreCase("put-point")) {
putPoint(requestObject, out);
} else if (action.equalsIgnoreCase("get-point")) {
getPoint(requestObject, out);
} else if (action.equalsIgnoreCase("update-point")) {
updatePoint(requestObject, out);
} else if (action.equalsIgnoreCase("query-rectangle")) {
queryRectangle(requestObject, out);
} else if (action.equalsIgnoreCase("query-radius")) {
queryRadius(requestObject, out);
} else if (action.equalsIgnoreCase("delete-point")) {
deletePoint(requestObject, out);
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
log(sw.toString());
}
}
private void putPoint(JSONObject requestObject, PrintWriter out) throws IOException, JSONException {
GeoPoint geoPoint = new GeoPoint(requestObject.getDouble("lat"), requestObject.getDouble("lng"));
AttributeValue rangeKeyAttributeValue = new AttributeValue().withS(UUID.randomUUID().toString());
AttributeValue schoolNameKeyAttributeValue = new AttributeValue().withS(requestObject.getString("schoolName"));
PutPointRequest putPointRequest = new PutPointRequest(geoPoint, rangeKeyAttributeValue);
putPointRequest.getPutItemRequest().addItemEntry("schoolName", schoolNameKeyAttributeValue);
PutPointResult putPointResult = geoDataManager.putPoint(putPointRequest);
printPutPointResult(putPointResult, out);
}
Try like that.
JSONObject jsonobj = new JSONObject();
JSONObject geoJsonObj = new JSONObject();
try {
jsonobj.put("action","put-point");
geoJsonObj.put("lng", longitude);
geoJsonObj.put("lat", latitude);
geoJsonObj.put("rangeKey", rangeKey);
geoJsonObj.put("schoolName", "TESTSCHOOL535353");
jsonobj.put("request", geoJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
new SendData().execute(jsonobj.toString());
public class SendData extends AsyncTask<String, Integer, Double>{
String response="";
#Override
protected Double doInBackground(String... params) {
postData(params[0]);
}
public void postData(String jsondata) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost=new HttpPost("url");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json",jsondata));
httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse res = httpclient.execute(httpPost);
InputStream content = res.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
System.out.println("response from server"+response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
SERVER SIDE-
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jsondata=request.getParameter("json");
//now parse your data from json
try {
JSONObject JsonObject=new JSONObject(jsondata);
JSONObject object=JsonObject.getJSONObject("request");
String action=object.getString("action");
String lng=object.getString("lng");
String lat=object.getString("lat");
String rangeKey=object.getString("rangeKey");
String schoolName=object.getString("schoolName");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I hope this will help you...!
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(PROJECT_ID, params[0]));
nameValuePairs.add(new BasicNameValuePair(BROKER_ID,params[1]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
StringBuilder responseJsonStr = new StringBuilder();
while ((output = br.readLine()) != null) {
responseJsonStr.append(output);
}
String queryString = Utils.getQueryString(nameValuePairs);
System.out.println("Query String "+URL +"&"+queryString);
//System.out.println("response Json String "+responseJsonStr );
if(!StringUtils.startsWith(responseJsonStr.toString(), "[")) {
responseJsonStr.insert(0,"[");
responseJsonStr.append("]");
}
try this:
public String getJson(Context applicationContext,String url) {
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("response_key",PrefernceSettings.getRestKey()));
nameValuePair.add(new BasicNameValuePair("response_request","auto_payments"));
Log.e("",String.valueOf(nameValuePairs));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
if(is != null){
result = convertInputStreamToString(is);
Log.e("result", result);
}else{
result = "Did not work!";
}
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
public String convertInputStreamToString(InputStream inputStream) {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
try {
while((line = bufferedReader.readLine()) != null)
result += line;
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
Try using this function:
public boolean postJSON(JSONObject jsonobj) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost("YOUR URL HERE");
StringEntity se = new StringEntity(jsonobj.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
httpPostRequest.setHeader("Accept-Encoding", "gzip");
//Send Http request
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
HttpEntity entity = response.getEntity();
String resonseStr = EntityUtils.toString(entity);
return getResponse(resonseStr);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
0D
where getResponse is a function that gets the response string and parses it and returns true or false according to how you define the web service.

How to send variables to PHP from Android to do a SELECT ... WHERE in PHP

I already got a method to read data from mysql and display it into my android app in textview's. The problem is that now I just retrieve all data from the database without doing a select ... where , just a select. I want to do a select ... where using the variables sent from my android app. I already use the folowing code in my login to send username and pass
nameValuePairs=new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("utilizator",utilizator.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("parola",parola.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
In the method I use I have 2 java files. I really don't understand them much ... so I don't know where to add the code to send variables to php.
httprequest.java
public class httprequest {
static int TIMEOUT = 5000;
public String read_url_resource(String _s_url)
{
String s_response_ = "";
BufferedReader br_reader=null;
StringBuilder sb_builder = new StringBuilder();
URL u_url = null;
try {
if ( _s_url==null || _s_url.length()==0)
return "";
//this.log_message("Downloading from "+_s_url, false);
u_url = new URL(_s_url);
HttpURLConnection huc_urlConnection = null;
huc_urlConnection = (HttpURLConnection)u_url.openConnection();
if ( huc_urlConnection!=null){
huc_urlConnection.setConnectTimeout(TIMEOUT);
huc_urlConnection.setReadTimeout(TIMEOUT);
huc_urlConnection.setUseCaches(false);
huc_urlConnection.setDoOutput(false);
InputStream is_input_stream = huc_urlConnection.getInputStream();
#SuppressWarnings("unused")
URL oURL = huc_urlConnection.getURL();
int i_response_code=huc_urlConnection.getResponseCode();
if ( i_response_code==200){
br_reader = new BufferedReader(new InputStreamReader(is_input_stream));
String line="";
while ((line = br_reader.readLine()) != null)
sb_builder.append(line);
is_input_stream.close();
s_response_ = sb_builder.toString();
String s_auth= huc_urlConnection.getURL().getAuthority();
}
}
} catch (Exception e) {
if ( e!=null )
Log.e("URL PROBLEM", e.toString());
s_response_ = "[\"error\": \"No connection\"]";
}
return s_response_;
}
}
and ReadJSONData.java
public class ReadJSONData extends AsyncTask<String, Integer, Integer> {
private String server = "http://asociatia-online.esy.es/cote.php?hc_location=ufi";
private ReadJSONListener jsonListener;
private String json ="";
private int internal_categ;
httprequest request;
public interface ReadJSONListener
{
void onTaskFinished(String s_json, int _i_internal_category);
}
public ReadJSONData (ReadJSONListener _jsonListener, int _i_internal_category)
{
this.jsonListener=_jsonListener;
this.internal_categ =_i_internal_category;
}
#Override
protected Integer doInBackground(String... strings) {
request = new httprequest();
this.downloadResource();
return null;
}
private void downloadResource() {
switch (this.internal_categ) {
case 1:
this.json = request.read_url_resource(server);
break;
}
}
#Override
protected void onPostExecute(Integer result)
{
this.jsonListener.onTaskFinished(this.json, this.internal_categ);
}
}
So, where to add the 4 lines code to send variables? In which file and where. Thanks !
With this code you can send variables to PHP and get some data back and store it in strings to use as you want.
private class ObtinereInformatii extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://asociatia-online.esy.es/rezumat.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("luna_rezumat",spinner_luna.getSelectedItem().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("an_rezumat",spinner_an.getSelectedItem().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("-------",result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
protected void onPostExecute(String result){
try{
jArray = new JSONArray(result);
readJson(jArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void readJson(JSONArray ja_data) throws JSONException {
if (ja_data!=null)
{
for (int i = 0; i<ja_data.length(); i++)
{
JSONObject jo = ja_data.getJSONObject(i);
if (jo.has("data_rezumat"))
{
if (jo.getString("data_rezumat")!=null)
{
z_data_rezumat= jo.getString("data_rezumat");
}
}
}
}
}

how to obtain a JSESSIONID cookie

I have an android client and this is how I am doing a request to my tomcat server:
protected String executeRequest(String url)
{
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
String output = "", line = "";
try
{
HttpGet getRequest = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
try
{
getRequest = new HttpGet(url);
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200)
{
response.getStatusLine().getStatusCode();
return null;
}
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
while ((line = br.readLine()) != null)
{
output += line;
}
httpClient.getConnectionManager().shutdown();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
Log.w(TAG, e.getMessage());
}
catch (IllegalStateException e)
{
e.printStackTrace();
Log.w(TAG, e.getMessage());
}
catch (IOException e)
{
e.printStackTrace();
Log.w(TAG, e.getMessage());
}
if(output.equals(""))
{
output = null;
}
return output;
}
Now I want to be able to get the JSESSIONID cookie. I understand that I need to provide with a cookie like explained here, but how do I get the jSessionId in the first time?
Thanks!
Ok, here is how I did it. Don't know if there is any easier way:
HttpResponse response = httpClient.execute(getRequest);
Header[] headers = response.getHeaders("Set-Cookie");
for(int i = 0; i < headers.length; i++)
{
if(headers[i].getName().equals("Set-Cookie"))
{
String pattern1 = "JSESSIONID=";
String pattern2 = ";";
Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
Matcher m = p.matcher(headers[i].getValue());
if(m.find())
{
sessionId = m.group(1);
break;
}
}
}

JSON parsing issue with Gujarati font in Android text view

I have developed an application, that has text view for display some Gujarati text from the JSON URL and data stored in PHP MySQL server database.
So, problem with display Gujarati font:
My code of JSON http is here:
public class CustomHttpClient {
public static final int HTTP_TIMEOUT = 30 * 1000;
private static HttpClient mHttpClient;
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;
}
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()));
// in = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8000);
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) {
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
and main activity code here:
desc_about=(TextView)v.findViewById(R.id.textdesc);
Typeface tf=Typeface.createFromAsset(getActivity().getAssets(),"Shruti.ttf");
desc_about.setTypeface(tf);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("temple_id","2"));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
url_temple,postParameters);
String result = response.toString();
try {
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
about_temple=json_data.getString("about_text");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
try{
desc_about.setText(about_temple);
}
catch(Exception e){
Log.e("log_tag","Error in Display!" + e.toString());;
Toast.makeText(getActivity(), "error" + 2, 100).show();
}
}
catch (Exception e) {
Log.e("log_tag","Error in http connection!!" + e.toString());
Toast.makeText(getActivity(), "error" + 3, 100).show();
}
Try using utf-endcoding at the time of making JSON on php side and same way decode utf in android side. I solved it using this way in iOS app, Thanks
Try this solution
StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://floming.com/shayri/guj_romanse.json", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String str = "";
try {
str = new String(response.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String decodedStr = Html.fromHtml(str).toString();

Categories