Check if POST is succesfull (Android) [duplicate] - java

This question already has answers here:
Android, Java: HTTP POST Request
(8 answers)
Closed 7 years ago.
I am doing a post request in Android. It should give me a response in the form of a string. Thats what i do to check it. However it gives me an empty string back. It's in the toast message. Am i doing something wrong, any hints for me guys?
private void makePostRequest() throws UnsupportedEncodingException {
SharedPreferences postpreference = this.getSharedPreferences("preferences", MODE_PRIVATE);
String password = postpreference.getString("Password", null);
String username = postpreference.getString("Username", null);
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
String text = "";
BufferedReader reader = null;
try {
// send post data request
URL url = new URL("secreturl but working");
URLConnection conn = url.openConnection();
OutputStreamWriter streamWriter = new OutputStreamWriter(conn.getOutputStream());
streamWriter.write(data);
streamWriter.flush();
//read the response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
// Show response on activity
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}

Check for response code. Then only get the response if you are getting the correct response code.
int responseCode = conn.getResponseCode();

I fixed it following the first solution in this link : Android, Java: HTTP POST Request
Thanks for help
Edit : Correct way to do the post request.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}

Related

How to Update to Thingspeak 401 Authorization Error

Im trying to Update JSON data to Thingspeak channel, but i get 401 error Authorization error. Have sent "writekey" as parameter. Error is
{"status":"401","error":{"error_code":"error_auth_required","message":"Authorization Required","details":"Please provide proper authentication details."}}
` try {
List<NameValuePair> nvPairList = new ArrayList<NameValuePair>();
NameValuePair nv5 = new BasicNameValuePair("writeApi_Key",writeApi_Key);
nvPairList.add(nv5);
HttpClient client = HttpClientBuilder.create().build();
HttpPut put= new HttpPut(urlname);
URI uri = null;
try {
uri = new URIBuilder(put.getURI()).addParameters(nvPairList).build();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
put.setURI(uri);
put.setHeader("writeApi_Key", writeApi_Key);
put.setHeader(HTTP.CONTENT_TYPE, "application/json");
put.setHeader("charset", "utf-8");
put.setHeader("Connnection", "keep-alive");
put.setHeader("Cache-Control", "no-cache");
System.out.println("Url header of post:::"+put.toString());
StringEntity entity = new StringEntity(entryobj.toString());
put.setEntity(entity);
System.out.println("Url header of post:::"+put.toString());
HttpResponse response = client.execute(put);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
System.out.println("connection refused");
} else if (response.getStatusLine().equals("0")) {
System.out.println("Update Failed");
}
HttpEntity responseentity = response.getEntity();
String responseString = EntityUtils.toString(responseentity, "UTF-8");
System.out.println(responseString);
} catch (ClientProtocolException cpe) {
cpe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} `
output url is when writeApi_Key and api_key respectively checked outputs are below
Url header of post:::PUT https://api.thingspeak.com/channels/230391.json?writeApi_Key=UEDXXXXXXXXXXXXX HTTP/1.1
Url header of post:::PUT https://api.thingspeak.com/channels/230391.json?api_key+=VG2XXXXXXXXXXXXX HTTP/1.1
Kindly looking for some one who can shed throw light.. Thanks you so much..
Check to make sure that your API key is correct. Many people who have this problem are using zeros ('0') instead of the letter 'O', and vice-versa. '1' and 'l' can be a problem as well.

Cannot save the data to the url using json

My json code { "Status": "NO UPDATES" }
Iam getting the output as couldn't save the data.
JSONResult iam getting as "FAILED"-- when i check the log.v(jsonresult,"jsonResult")
iam unable to solve the issue
please help me out.
btn_Save.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{try
{StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String postReceiverUrl = "http://";
Log.v(TAG, "postURL: " + postReceiverUrl);
// HttpClient
#SuppressWarnings("resource")
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
Log.v(TAG, jsonobject.toString());
nameValuePairs.add(new BasicNameValuePair("EmployeeId", wepemployeeDeptId.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("visitorname", wepName.getText().toString()));
Log.v(TAG, "Visitor Name: " + wepName.getText().toString());
nameValuePairs.add(new BasicNameValuePair("PhoneNo", wepMobile.getText().toString()));
// nameValuePairs.add(new BasicNameValuePair("WhomToMeet", wepWhomToMeet.getSelectedItem().toString()));
nameValuePairs.add(new BasicNameValuePair("Address", wepAddress.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("EmailID", wepEmail.getText().toString()));
// nameValuePairs.add(new BasicNameValuePair("visitType", wepVisitType.getSelectedItem().toString()));
nameValuePairs.add(new BasicNameValuePair("PurposeOfMeet", wepPurpose.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("DateofVisit", wepVisitDate.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("Intime", wepInTime.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("Outtime", wepOutTime.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("BadgeNo", wepBadgeNumber.getText().toString()));
// nameValuePairs.add(new BasicNameValuePair("CreatedBy", wepcreatedby.getText().toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
Log.i("jsonResult",jsonResult);
JSONObject object = new JSONObject(jsonResult);
String status = object.getString("Status").trim();
Toast.makeText(getBaseContext(), "Please wait...",100).show();
if(status.toString().equals("SUCCESS"))
{
Intent i = new Intent(Entry.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
Toast.makeText(getBaseContext(), "Details Inserted",1000000).show();
}
if(status.toString().equals("FAILED"))
{
Toast.makeText(getBaseContext(), "Couldn't save the data...",1000000).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
String data = null;
try {
data = URLEncoder.encode("EmployeeId", "UTF-8")
+ "=" + URLEncoder.encode(wepemployeeDeptId.getText().toString(), "UTF-8");
data += "&" + URLEncoder.encode("visitorname", "UTF-8") + "="
+ URLEncoder.encode(wepName.getText().toString()), "UTF-8");
//add key according to your requirement
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL("Your URL");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();EmployeeId

Java (Android) HTTP Post to PHP Page

This is for an Android application ,where my mobile developer is trying to post json data to my PHP page .
Below is the function that is being used :
public static String postData(String url, String postData) {
// Create a new HttpClient and Post Header
InputStream is = null;
StringBuilder sb = null;
String result = "";
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new StringEntity(postData));
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// Execute HTTP Post Request
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());
//throw new CustomException("Could not establish network connection");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 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();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
//throw new CustomException("Error parsing the response");
}
return result;
}
Where url is the link to my php webpage . On my php page , i am just trying to print out the posted data by doing :
print_r($_POST);
But it shows an empty array . I even tried using the REST addon for firefox and doing the same but it simply shows a blank array .
Would be great if someone could point out if i am missing anything .
Thanks.
you need to get the json content like below :
if(isset($_POST))
{
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);
echo $jsonObj;
}

Connecting to PHP script through android app [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
This is the code I have so far.
public void postData(String toPost) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mywebsite.com/dev/reverser.php");
//This is the data to send
String MyName = toPost; //any data to send
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("action", MyName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//This is the response from a php application
String reverseString = response;
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
}
}//end postData()
Can somebody please tell me what is wrong in the following code! I have established that there is a problem in the try catch block only and not anywhere else in the activity. I just do not know what it is or how to correct it.
My PHP code is quite simple. It is something like this -
//code to reverse the string
$reversed = strrev($_POST["action"]);
echo $reversed;
In a comment above you indicated that you are getting a android.os.NetworkOnMainThreadException.
In the most recent versions of Android you are not allowed to do networking on the main thread as it makes the UI unresponsive. Move your code to a different thread using AsyncTask (see the Android developer guide for details) or some other mechanism.
Adding as a seperate answer as the poster requests to do so .
Assumption :
a ) There is a text box that accepts the URL to load
b ) A button which when clicked performs the networking operation on the URL fetched f
Implement a button click listener that calls the following function :
private void URL()
{
String url = txtURL.getText().toString();
new URLTask().execute(new String[] { url });
}
private class URLTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... urls)
{
BufferedReader br = null;
String url = urls[0];
StringBuffer sb = new StringBuffer("");
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(url));
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "value of param1"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
String line;
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
}
catch(Exception e)
{
Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
return(sb.toString());
}
protected void onPostExecute(String result)
{
txtContent.setText(result);
}
You need to implement onPostExecute as well . There are other APIS .
Android Async Task Documentation
Try printing out the exception .
Use this code to print out your response . Check the status of the response
HttpResponse response = client.execute(request);
String line;
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
}
catch(Exception e)
{
Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
Tell us the exception . It would be easy to pinpoint your problems then .
EDIT : ANSWER :
You are trying to perform a networking operation on the MAIN thread . This is an illegal thing to do . Create a AsyncTask i.e create a seperate thread to do your networking operations .
Android Details of the exception
Stackoverflow question

Post url from android to retrieve data

i have a url "http://184.82.158.234/~store/rest/system/connect.json" and posting this url with mozilla addon called poster returns data in form of json
what i want is to post this url from android to get that json data into androids view .
any help is highly appreciated
thanks
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://184.82.158.234/~store/rest/system/connect.json");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
response variable will contain your json data.
Here is a function maybe you can use to post a string to a URL.
public String doHttpPost(final String fullUrl, final String body) {
final URL url = new URL(fullUrl);
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// set the request mode as POST
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept-charset", "utf-8");
urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
final DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream());
// write the body.
request.writeBytes(body);
// flush output buffer
request.flush();
request.close();
// construct a read using input stream and charset.
final InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream(), CHARSET_UTF8);
final BufferedReader in = new BufferedReader(isr);
String inputLine;
final StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
stringBuilder.append(inputLine).append("\n");
}
in.close();
isr.close();
urlConnection.disconnect();
return stringBuilder.toString();
}
check below code: try this it may help you.
ArrayList nameValuePairs1 = new ArrayList();
nameValuePairs1.add(new BasicNameValuePair("user_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_review",""+text));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity entity = responce.getEntity();
is = entity.getContent();
BufferedReader bufr = new BufferedReader(new InputStreamReader(is1,"iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(bufr.readLine() + "\n");
String line = "0";
while ((line = bufr.readLine()) != null)
{
sb.append(line + "\n");
}
is1.close();
result = sb.toString();
result is a json String. parse that json and display in any control. i displaied that in text view see below.
final MyProgressDialog progDailog = new MyProgressDialog(Cheking_Review.this);
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (Name.length() > 0 && Name != null) {
txtvenue.setText(Name);
} else {
txtvenue.setText(venue_name);
}
}
};
new Thread() {
public void run() {
try {
// put your result here
JSONObject jObject = new JSONObject(result);
JSONObject menuObject = jObject.getJSONObject("response");
JSONObject venueObject = menuObject.getJSONObject("venue");
Name = venueObject.getString("name");
String id = venueObject.getString("id");
Log.d("--------name---------", Name);
Log.d("--------id---------", id);
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();

Categories

Resources