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
Related
I save data to mysql db with php and json but my data convert to ? ,I use utf-8 in php and db connect and java code
php
<?php
header("Content-type: application/json; charset=utf-8");
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
$hostname='localhost';
$username='ekht3r44_6785h5h';
$password='IFVB!8Nw{#-S';
$response = array();
.
.
.
$dbh=new PDO("mysql:host=$hostname;dbname=db;charset=utf8mb4",$username,$password);
$sql="INSERT INTO contact_form (name,email,subject,message) VALUES (".$_POST['name'].",".$_POST['email'].",".$_POST['subject'].",".$_POST['message'].");";
$statement = $dbh->prepare("INSERT INTO contact_form (name,email,subject,message) VALUES (:name,:email,:subject,:message);");
$statement->execute(array(':name' => $_POST['name'],':email' => $_POST['email'],':subject' => $_POST['subject'],':message' => $_POST['message']));
.
.
.
?>
java
protected String doInBackground(String... args) {
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", et_name.getText().toString()));
params.add(new BasicNameValuePair("email", et_email.getText().toString()));
params.add(new BasicNameValuePair("subject", et_subj.getText().toString()));
params.add(new BasicNameValuePair("message", et_msg.getText().toString()));
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
page_output = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return page_output;
}
Can you please check where has it gone wrong.
Please check the charset of your table in MySQL. That "might" be the cause.
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
}
I am developing an android app, I have run into a situation where the app will use an API to send some data to the php webservice and the webservice will greate some json encoded message which will be echoed back.
My question is
How Do I store this json message that was sent by php echo into a variable in the android app?
How Do I then go about parsing the json and use the data to construct a switch case?
I had raised a similar question sometime back and was told to use AsyncTask but what I don't understand is why would I need to use it.
The sample json response that will be sent by the phpwebservice is
{"error":false,"message":"New user created"}
I want to be able to get the error variable and decide if there is any error and also get the message in a variable and display it to the user in the app.
I currently have the android signup.java code like this
public void post() throws UnsupportedEncodingException
{
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
if (password.equals(confirmpass)) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httppost);
//Code to check if user was successfully created
final int statusCode = httpResponse.getStatusLine().getStatusCode();
switch (statusCode)
{
case 201:
Toast.makeText(getBaseContext(), "Successfully Registered", Toast.LENGTH_SHORT).show();
break;
case 400:
Toast.makeText(getBaseContext(), "Username already taken", Toast.LENGTH_SHORT).show();
username.setText("");
break;
default:
Toast.makeText(getBaseContext(), "Unknown error occurred", Toast.LENGTH_SHORT).show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}
While this checks the http header code and might work( I havent tested it out) I want to use the jsnon response and do the handling using it.
Use java-json:
HttpURLConnection urlConnection = (HttpURLConnection) (uri.toURL().openConnection());
urlConnection.setConnectTimeout(1500);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", uname));
params.add(new BasicNameValuePair("pass", password));
params.add(new BasicNameValuePair("email", email));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
urlConnection.connect();
if(urlConnection.getResponseCode() == 200){
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject json = new JSONObject(responseStrBuilder.toString());
String message = json.getString("message");
}
I'm trying to make a POST request to a server in my Android app, but it ain't happening. Below is the code -
try{
View p = (View) v.getRootView();
EditText usernamefield = (EditText)p.findViewById(R.id.username);
String username = usernamefield.getText().toString();
EditText passwordfield = (EditText)p.findViewById(R.id.pass);
String password = passwordfield.getText().toString();
String apiKey = "ac96d760cb3c33a1ee988750b0b2fd12";
String secret = "cd9118e8d1d32d003e0ed54a202c2bf8";
Log.i(TAG,password);
String authToken = computeMD5hash(username.toLowerCase()).toString()+computeMD5hash(password).toString();
String authSig = computeMD5hash("api_key"+apiKey+"authToken"+authToken+"method"+"auth.getMobileSession"+"username"+username+secret).toString();
Log.i(TAG,authToken);
HttpClient client = new DefaultHttpClient();
Log.i(TAG,"after client1");
HttpPost post = new HttpPost("http://ws.audioscrobbler.com/2.0/");
Log.i(TAG,"after client2");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "auth.getMobileSession"));
nameValuePairs.add(new BasicNameValuePair("api_key", apiKey));
nameValuePairs.add(new BasicNameValuePair("api_sig", authSig));
nameValuePairs.add(new BasicNameValuePair("format", "json"));
nameValuePairs.add(new BasicNameValuePair("authToken", authToken));
nameValuePairs.add(new BasicNameValuePair("username", username));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i(TAG,post.getURI().toString()); //logs the URL
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
Log.i(TAG,"Status code is"+status);
Log.i(TAG,"after post");
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
if(response.getStatusLine().getStatusCode()!= org.apache.commons.httpclient.HttpStatus.SC_OK)
{
Log.i(TAG,"bad http response");
Toast.makeText(getApplicationContext(),"bad httpcode",Toast.LENGTH_LONG).show();
throw new Exception(response.getStatusLine().getReasonPhrase());
}
StringBuilder sb = new StringBuilder();
String s;
while(true)
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
ips.close();
System.out.print(sb.toString());
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
catch(NoSuchAlgorithmException e)
{
}
catch(Exception e){
}
The code executes till the Log.i(TAG,post.getURI().toString()) log statement. It'll print out the URL that is made - http://ws.audioscrobbler.com/2.0/. No parameters attached (which is weird).
I don't know what's wrong with my implementation for adding parameters to URL using NameValuePairs.
I do have one simple method to post data to server. Please use it and let me know if that is useful to you or not:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "auth.getMobileSession"));
nameValuePairs.add(new BasicNameValuePair("api_key", apiKey));
nameValuePairs.add(new BasicNameValuePair("api_sig", authSig));
nameValuePairs.add(new BasicNameValuePair("format", "json"));
nameValuePairs.add(new BasicNameValuePair("authToken", authToken));
nameValuePairs.add(new BasicNameValuePair("username", username));
//call to method
JSONObject obj = makeHttpRequest(nameValuePairs, "http://ws.audioscrobbler.com/2.0/", "POST");
public static JSONObject makeHttpRequest(List<NameValuePair> params, String url, String method) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
url = url.trim();
Log.e("FETCHING_DATA_FROM",""+url.toString());
HttpPost httpPost = new HttpPost(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 600000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 600000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
if(params!=null){
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
Log.e("FETCHING_DATA_FROM",""+url.toString());
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 600000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 600000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
You must have wrapped this code in a try catch block since there are several possible exceptions thrown here. As to which is the problem I am not sure, but here are some common ones that could cause a problem and you need to give more info before we can see which one it is:
1) On newer versions of Android if you make thisw call in the main UI thread it will throw an exception a NetworkOnMainThread exception. You must do networking code on a background thread.
2) You did not declare the Internet permission in your manifest so it will throw a security exception.
You need to look at the logcat for an exception or break in the catch part of your try/catch. If your catch looks like this:
catch(Exception e)
{
}
Then it will silently eat the exception and give you no indication of the problem.
Just try with JsonStringer.Like:
HttpPost request = new HttpPost("http://ws.audioscrobbler.com/2.0/something_here");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
JSONStringer vm;
try {
vm = new JSONStringer().object().key("method")
.value("auth.getMobileSession").key("api_key").value(apikey)
.key("api_sig") .value(authSig).key("format").value("json").key(authToken).value(authToken).key("username").value(username)
.endObject();
StringEntity entity = new StringEntity(vm.toString());
request.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Also as Kaediil said make try and catch clause with your response code.
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();