I'm trying to add GET params to my code so it will append this URL
"http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?";
to somthing like this
http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=nearest&lat=53.472128&long=-2.239928
The params are:
op
nearest
lat
long
Here's my Service handler code which handles the URL and appends the POST and GET methods.
package com.white.alice.myapplication;
/** HTTP CALL HANDLER **/
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class Near {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public Near() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
params.add(new BasicNameValuePair("op", "nearest"));
// 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've already made a List<NameValuePair> params). But each time I try to add a list item or param with params.add(new BasicNameValuePair("key", "value"));. it causes my APP to crash. Am I placing the params.add(new BasicNameValuePair("key", "value")); in the wrong place causing my app to crash? or am I using a incorrect method to add my params to a URL?
0 comments:
Post a Comment