HttpUrlConnection PUT method doesn't work - java

I've done the following client application to consume REST services (a PUT method) using AppacheHttpClient (it's working) :
public class UserLogin {
private static final String URL = "http://192.168.1.236:8080/LULServices/webresources";
public static void main(String[] args) throws Exception {
final DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 8080),
new UsernamePasswordCredentials("xxxxx", "xxxxx"));
HttpPut httpPut = new HttpPut(URL + "/services.users/login");
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
httpPut.addHeader("Content-type", "multipart/form-data");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("login", "xxxxx"));
nameValuePairs.add(new BasicNameValuePair("password", "xxxxx"));
httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httpPut);
try {
HttpEntity entity = response.getEntity();
String putResponse = EntityUtils.toString(entity);
System.out.println("Login successful! Secret id: " + putResponse);
EntityUtils.consume(entity);
} finally {
httpPut.releaseConnection();
}
} finally {
httpclient.getConnectionManager().shutdown();
}
}
}
Now I want to do the same, using HttpUrlConnection, but is not working:
public class PUTmethod {
public static void main(String[] args) throws Exception
{
HttpURLConnection urlConnection = null;
try {
String webPage = "http://localhost:8080/LULServices/webresources/services.users/login";
Authenticator myAuth = new Authenticator()
{
final static String USERNAME = "xxxxx";
final static String PASSWORD = "xxxxx";
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(USERNAME, PASSWORD.toCharArray());
}
};
Authenticator.setDefault(myAuth);
URL urlToRequest = new URL(webPage);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("PUT");
urlConnection.setRequestProperty("Content-type", "multipart/form-data");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("login", "xxxxx"));
nameValuePairs.add(new BasicNameValuePair("password", "xxxxx"));
OutputStream out = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(getQuery(nameValuePairs));
writer.close();
out.close();
urlConnection.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("Failure processing URL");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
public static String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
System.out.println(result.toString());
return result.toString();
}
}
By not working I mean that no errors appear, but the PUT doesn't work, like when I use the ApacheHttpClient solution. What is wrong with my code?
Thanks.

Try calling urlConnection.getResponseCode(); after urlConnection.connect(); to force a flush of the underlying outputstream and reading the inputsream.

Try set
urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
after
urlConnection.setRequestMethod("PUT");

Related

how pass String parameter to url

i need to pass to this URL a parameter http://192.168.1.15:8888/android_login_api/getsPreferiti.php?id="+mParam1
where mParam1 contains this String 5a325bc1b214c5.50816853
how can i do?
PS:now i get this: Response from url: {"error":false,"message":"VIDEOs fetched successfully.","pdfs":[]} but pdfs array have pdfs
Add parameters to HTTPURL Connection using HTTPPost
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("parameter1", parameterValue1));
params.add(new BasicNameValuePair("parameter2", parameterValue2));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
private String getQuery(List<NameValuePair> params) throws
UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
String response = null;
int GET = 1;
int POST = 2;
try {
// 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();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
And you can call this method by using AsyncTask as follow:
try {
JSONObject jData = new JSONObject();
String mParam = "5a325bc1b214c5.50816853";
jData.put("id", mParam);
List<NameValuePair> params1 = new ArrayList<NameValuePair>(2);
params1.add(new BasicNameValuePair("data", jData.toString()));
response = makeServiceCall("http://192.168.1.15:8888/android_login_api/getsPreferiti.php", 1, params1);
} catch (JSONException e) {
e.printStackTrace();
}

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.

Android : Web request helper class

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

HTTP POST request with JSON String in JAVA

I have to make a http Post request using a JSON string I already have generated.
I tried different two different methods :
1.HttpURLConnection
2.HttpClient
but I get the same "unwanted" result from both of them.
My code so far with HttpURLConnection is:
public static void SaveWorkflow() throws IOException {
URL url = null;
url = new URL(myURLgoeshere);
HttpURLConnection urlConn = null;
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.connect();
DataOutputStream output = null;
DataInputStream input = null;
output = new DataOutputStream(urlConn.getOutputStream());
/*Construct the POST data.*/
String content = generatedJSONString;
/* Send the request data.*/
output.writeBytes(content);
output.flush();
output.close();
/* Get response data.*/
String response = null;
input = new DataInputStream (urlConn.getInputStream());
while (null != ((response = input.readLine()))) {
System.out.println(response);
input.close ();
}
}
My code so far with HttpClient is:
public static void SaveWorkflow() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(myUrlgoeshere);
StringEntity input = new StringEntity(generatedJSONString);
input.setContentType("application/json;charset=UTF-8");
postRequest.setEntity(input);
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
postRequest.setHeader("Accept", "application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Where generated JsonString is like this:
{"description":"prova_Process","modelgroup":"","modified":"false"}
The response I get is:
{"response":false,"message":"Error in saving the model. A JSONObject text must begin with '{' at 1 [character 2 line 1]","ids":[]}
Any idea please?
Finally I managed to find the solution to my problem ...
public static void SaveWorkFlow() throws IOException
{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(myURLgoesHERE);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("task", "savemodel"));
params.add(new BasicNameValuePair("code", generatedJSONString));
CloseableHttpResponse response = null;
Scanner in = null;
try
{
post.setEntity(new UrlEncodedFormEntity(params));
response = httpClient.execute(post);
// System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
in = new Scanner(entity.getContent());
while (in.hasNext())
{
System.out.println(in.next());
}
EntityUtils.consume(entity);
} finally
{
in.close();
response.close();
}
}
Another way to achieve this is as shown below:
public static void makePostJsonRequest(String jsonString)
{
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost postRequest = new HttpPost("Ur_URL");
postRequest.setHeader("Content-type", "application/json");
StringEntity entity = new StringEntity(jsonString);
postRequest.setEntity(entity);
long startTime = System.currentTimeMillis();
HttpResponse response = httpClient.execute(postRequest);
long elapsedTime = System.currentTimeMillis() - startTime;
//System.out.println("Time taken : "+elapsedTime+"ms");
InputStream is = response.getEntity().getContent();
Reader reader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
while (true) {
try {
String line = bufferedReader.readLine();
if (line != null) {
builder.append(line);
} else {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
//System.out.println(builder.toString());
//System.out.println("****************");
} catch (Exception ex) {
ex.printStackTrace();
}
}

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