Android : Web request helper class - java

I need to good class for sending and handling the all request such as get , post
I researched anywhere but i could not find the good helper class for it , i am beginner in java and android , please share a good connection helper class with me

public class RRequestHelper
{
DefaultHttpClient httpClient;
HttpContext localContext;
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
HttpGet httpGet = null;
public RRequestHelper()
{
this.setDefaultOptions();
}
public void setDefaultOptions()
{
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, RGeneralSettings.getInstance().getSettingInt(RConstants.CONNECTION_TIMEOUT, false));
HttpConnectionParams.setSoTimeout(myParams, RGeneralSettings.getInstance().getSettingInt(RConstants.CONNECTION_TIMEOUT, false));
httpClient = new DefaultHttpClient(myParams);
localContext = new BasicHttpContext();
}
public void clearCookies()
{
httpClient.getCookieStore().clear();
}
public void abort()
{
try
{
if (httpClient != null)
{
System.out.println("Abort.");
httpPost.abort();
}
}
catch (Exception e)
{
System.out.println("Your App Name Here" + e);
}
}
public String sendPost(String url, String data)
{
return sendPost(url, data, null);
}
public String sendJSONPost(String url, JSONObject data)
{
return sendPost(url, data.toString(), "application/json");
}
public String sendPost(String url, String data, String contentType)
{
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
Log.d("Your App Name Here", "Setting httpPost headers");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0");
httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
if (contentType != null)
{
httpPost.setHeader("Content-Type", contentType);
}
else
{
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
}
try
{
tmp = new StringEntity(data,"UTF-8");
}
catch (UnsupportedEncodingException e)
{
Log.e("Your App Name Here", "HttpUtils : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
Log.d("Your App Name Here", url + "?" + data);
try
{
response = httpClient.execute(httpPost,localContext);
if (response != null)
{
ret = EntityUtils.toString(response.getEntity());
}
}
catch (Exception e)
{
Log.e("Your App Name Here", "HttpUtils: " + e);
}
Log.d("Your App Name Here", "Returning value:" + ret);
return ret;
}
public String sendGet(String url) {
httpGet = new HttpGet(url);
try {
response = httpClient.execute(httpGet);
} catch (Exception e) {
Log.e("Your App Name Here", e.getMessage());
}
//int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
try {
ret = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
Log.e("Your App Name Here", e.getMessage());
}
return ret;
}
public InputStream getHttpStream(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
{
throw new IOException("Not an HTTP connection");
}
try
{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception e)
{
throw new IOException("Error connecting");
} // end try-catch
return in;
}
}

Related

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

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

Send Data from android app to php page

I am trying to successfully send data across from an android app to a php web app and display that data and save into a mysql database. However i don't get an exception or anything just the data i send across does not get received on the server end. My code is below:
public void onClick(View view) {
String text = "None";
switch (view.getId()) {
case R.id.btnOne:
send();
text = "Response Submitted";
break;
case R.id.btnTwo:
text = "Two";
break;
case R.id.btnThree:
text = "Three";
break;
case R.id.btnFour:
text = "Four";
break;
}
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private void send() {
URL a = null;
try {
a = new URL("http://cce.swlgroup.com/json.php/");
} catch (Exception exception) {
exception.printStackTrace();
}
new URLTestTask().execute(a);
}
private class URLTestTask extends AsyncTask<URL, Integer, Void> {
#Override
protected void doInBackground(URL... urls) {
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL("http://cce.swlgroup.com/json.php/");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
Log.e("", "" + conn.getResponseMessage());
conn.connect();
JSONObject obj = new JSONObject();
obj.put("Marge","Simpson");
HttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet(url.toURI());
post.setEntity(new ByteArrayEntity(obj.toString().getBytes("UTF8")));
post.setHeader("json",obj.toString());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String responseBody = client.execute(post,
responseHandler);
HttpEntity ent = post.getEntity();
InputStream stream = ent.getContent();
String result = RestClient.convertStreamToString(stream);
BufferedReader red = new BufferedReader(new InputStreamReader(ent.getContent()));
String line;
StringBuilder lb = new StringBuilder();
while((line = red.readLine()) != null){
lb.append(red);
}
red.close();
Log.i("Read from server", result);
} catch (Exception e){
e.printStackTrace();
}finally {
if (conn != null)
conn.disconnect();
try{
if (reader != null)
reader.close();
} catch (Exception e){
e.printStackTrace();
}
}
return null;
}
}
my php code is below to get data and display:
$json = file_get_contents('php://input');
$obj = json_decode($json);
var_dump($obj);
var_dump($_POST);
var_dump($_GET);
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL("http://10.0.2.2/json.php/");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
Log.e("", "" + conn.getResponseMessage());
conn.connect();
JSONObject obj = new JSONObject();
obj.put("Marge","Simpson");
HttpClient client = new DefaultHttpClient();
StringBuilder pat = new StringBuilder();
HttpGet post = new HttpGet(url.toURI());
post.setEntity(new ByteArrayEntity(obj.toString().getBytes("UTF8")));
post.setHeader("json", obj.toString());
post.setHeader("Content-Type", "application/json");
post.setHeader("accept-encoding","gzip, deflate");
post.setHeader("accept-language","en-US,en;q=0.8");
post.setHeader("FormData",obj.toString());
HttpResponse lazy = client.execute(post);
HttpEntity ent = lazy.getEntity();
String lb = EntityUtils.toString(ent);
pat.append(lb);
Log.i("Read from server", pat.toString());
} catch (Exception e){
e.printStackTrace();
}finally {
if (conn != null)
conn.disconnect();
try{
if (reader != null)
reader.close();
} catch (Exception e){
e.printStackTrace();
}
}
return null;
I made the change in accordance with that code but it doesnt seem to send a result across.

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 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;
}
}
}

Android web view not sending post array to php?

the problem is that i don't receive any $_POST['registerationID'] from android webview
i have this code in android java ::
#Override
protected void onRegistered(Context context, String registrationId) {
String URL_STRING = "http://mysite.org/mysite/index.php/user/notification/";
Log.i(MyTAG, "onRegistered: registrationId=" + registrationId);
// notification
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("registrationId",registrationId));
try{
HttpPost httppost = new HttpPost(URL_STRING);
httppost.setHeader("Content-Type","text/plain");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
HttpResponse response = httpclient.execute(httppost);
Log.i("LinkPOST:", httppost.toString());
Log.i("postData", response.getStatusLine().toString());
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null){
//System.out.println("Not Empty");
String responseBody = EntityUtils.toString(httpEntity);
System.out.println(responseBody);
} else {
System.out.println("Empty");
}
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
and i handle the httprequest post in php (using codeigniter) as the following :
function notification() {
$registrationId = $_POST['registrationId'];
if($this->session->userdata('emailid')) {
//echo 'working from inside the if statement'.$this->session->userdata('emailid');
//$query = $this->db->query('INSERT INTO user (`deviceid`) VALUES ('.$_GET['registerationID'].') where `emailid`='.$this->session->userdata('emailid').';');
$data = array(
'deviceid' => $registrationId,
);
$this->db->where('emailid', $this->session->userdata('emailid'));
$this->db->update('user', $data);
if($this->db->affected_rows() == 1) {
// some code
}
else {
// some code
}
}
Try with the function bellow. It works for me.
Just Fill a HashMap for your post params
private static void post(String url, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
Try replacing
httppost.setHeader("Content-Type","text/plain")
by
httppost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8")
which is expected by your php code.
For more detail please see this SO question

Categories