I am trying to insert UTF-8 characters(Like username in hindi or tamil language) in MySql with Codeigniter framework.
Here is my android side code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uploadApi);
try {
List<NameValuePair> nameValuePairs=new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("key1","विकिपीडिया"));
nameValuePairs.add(new BasicNameValuePair("key2","इण्टरनेट"));
UrlEncodedFormEntity form = new UrlEncodedFormEntity(nameValuePairs);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
and this is server side code in codeigniter:
public function create()
{
$name=$this->input->get_post("name") ;$text=$this->input->get_post("text");
$type=$this->input->get_post("type");$contact=$this->input->get_post("contact");
$mp=$this->input->get_post("mp");$mla=$this->input->get_post("mla");
$position=$this->input->get_post("position");
$config['upload_path'] = './uploads/';
$config['allowed_types'] = '*';
$config['max_size'] = '20000';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('image'))
{
$image="noimage.jpg";
echo $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
$image=$data['file_name'];
}
$data['json']=$this->uploadmodel->insert($name,$image,$text,$contact,$mp,$mla,$type,$position);
echo "Thanks for Sharing";
}
All configuration is set to utf-8 in configuration file.
error is i am getting all string like ?????????
please tell me where i am doing wrong.
Thanks
I added this line:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
Although i tried with it also before.
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
but the above runs successfully.
Related
I am new to android and I have a question about name value pairs that I am a little confused on. For example I am trying to post to the following example and get the response code using the endpoint:
/account/create/bank-id?ssn=SSN&name=NAME&email=EMAIL. I would edit the need to edit the following : bank-id , SSN , NAME, and EMAIL. at the moment. I am thinking along the lines of(so far no luck , no repsponse code are printing so I dont know what I am doing wrong at the moment, ty for any replies):
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xx.xxx.xxx/account/create/");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("bank-id", "12345"));
nameValuePairs.add(new BasicNameValuePair("ssn", "451"));
nameValuePairs.add(new BasicNameValuePair("name", "kitty"));
nameValuePairs.add(new BasicNameValuePair("name", "kitty"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
I need to send string (vietnamese) from Android devices to server like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.URL.UPDATE_CURRENT_STATUS);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("location", "Thạch thất Hanoi "));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int respnseCode = response.getStatusLine().getStatusCode();
if (respnseCode == 200) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
But when server gets the string, its not like
Thạch thất Hanoi
its become
Thạch Thất Hanoi
My code in server side:
#RequestMapping(value = "/UpdateCurrentStatus", method = RequestMethod.POST, produces = { "application/json" })
#ResponseBody
public MessageDTO updateCurrentStatus(
#RequestParam Map<String, String> requestParams) throws TNException {
String location = requestParams.get("location");
System.out.println(location);
MessageDTO result = driverBO.updateCurrentStatus(location);
return result;
}
How can I resolve this problem? Thank you.
Did you set you android httpclient Content-Type header to application/json; charset=utf-8 instead of "application/json"?
I think your problem is that the content entity location you sent is encoded correctly in UTF-8 but server failed to acknowledge UTF-8. clarify it in Content-Type header.
You can diagnose http content and its header with great http monitoring tool Fiddler.
-EDIT BELOW-
Relace your UrlEncodedFormEntity as below. Set header to application/json; charset=utf-8 as I described earlier. it's good to set it up still.
JSONObject jsonParam = new JSONObject();
jsonParam.put("location", "Thạch thất Hanoi ");
StringEntity entity = new StringEntity(jsonParam.toString(), "UTF-8");
httppost.setEntity(entity);
I want to build 2 same products for Android and iOs.
The iOs already works, but the android doesnt, that's because of the format of the string.
in iOs this is:
NSString*jsonString = [[NSString alloc] initWithFormat:#"{\"id\":\"%#\",\"longitude\":\"%#\",\"latitude\":\"%#\",\"timestamp\":\"%#\"}", _phonenumber, longitude , latitude, stringFromDate];
And i dont know how to do this exactely like this in android. The format here is different.
What i have now is:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("id", num));
nameValuePairs.add(new BasicNameValuePair("longitude", longi));
nameValuePairs.add(new BasicNameValuePair("latitude", lat));
nameValuePairs.add(new BasicNameValuePair("timestamp", time));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
Thanks in advance, i need this by the end of the week so if you could help me, that would be greatly appreciated
i get this as an result from the iOs string:
{
"id":"0612833398",
"longitude":"-143.406417",
"latitude":"32.785834",
"timestamp":"10-10 07:56"
}
Okay, this is what my problem is.
Yes i need to send this exact string to an asp.net file on a server. But i need to know how to combine this with this: with the http post to
HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php");
before i combined this with the nameValuePPairs like this
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Create same string as you are getting in IOS by create an JosnObject as:
JSONObject json = new JSONObject();
json.put("id", "0612833398");
json.put("longitude", "-143.406417");
json.put("latitude", "32.785834");
json.put("timestamp", "10-10 07:56");
now if you make a print for json object you will get this string :
{"id":"0612833398","longitude":"-143.406417","latitude":"32.785834",
"timestamp":"10-10 07:56"}
and Post JSONObject as to server :
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php");
httppost.setHeader("Content-type", "application/json");
// Create json object here...
JSONObject json = new JSONObject();
json.put("id", "0612833398");
json.put("longitude", "-143.406417");
json.put("latitude", "32.785834");
json.put("timestamp", "10-10 07:56");
/// create StringEntity with current json obejct
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
}
To create a String you can use String.format(). In this case the syntax is very similar to Objective-C:
String s = String.format("{\"id\":\"%s\",\"longitude\":\"%s\",\"latitude\":\"%s\",\"timestamp\":\"%s\"}", num, long, lat, time);
HTTP Post goes like this:
HttpPost postMethod = new HttpPost(url);
try {
HttpParams params = new BasicHttpParams();
params.setParameter(name, value);
postMethod.setParams(params);
httpClient.execute(postMethod);
} catch (Exception e) {
} finally {
postMethod.abort();
}
How do I send the data to this PHP file below? I can establish the connection and send data, but can't receive the response. I need to send 3 parameters, the "op", Username and password.
switch ($_POST["op"]) {
// User Authentication.
case 1:
$UName = $_POST["UName"];
$UPass = $_POST["UPass"];
$UPass = md5($UPass);
//....Some code
// New user registration process.
case 2:
$UName = $_POST["UName"];
$UPass = $_POST["UPass"];
$UEmail = $_POST["UEmail"];
$UNick = $_POST["UNick"];
$UPass = md5($UPass);
//....Some code
}
My code so far:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://SomeUrl/login.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("1", "dan"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d(TAG, ""+responseBody);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
What am I doing wrong?
Looking at your PHP code, at a bare minimum you need to specify an op parameter. Then depending on which op you're trying to carry out, make sure you specify the other needed parameters as well. For user authentication (op = 1):
nameValuePairs.add(new BasicNameValuePair("op", "1"));
nameValuePairs.add(new BasicNameValuePair("UName", "dan"));
nameValuePairs.add(new BasicNameValuePair("Pass", "somepass"));
On a side note, you should secure the PHP service with SSL, if you are using it to process sensitive user information.
Android HTTP POST should look like this:
HttpParams httpParams=new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
// Data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("UName", "dan"));
nameValuePairs.add(new BasicNameValuePair("UPass", "password"));
nameValuePairs.add(new BasicNameValuePair("op", "1"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://SomeUrl/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
}
In your PHP code I would strongly recommend to use mysql_real_escape_string($_POST['UName']) otherwise it is easy to attack via SQL injection.
I would also recommend to use either SSL connection (HTTPS) or to send the password only hashed (MD5)
I'm currently trying to send data via POST to a server, and the server is handling the data and appends it to a JSON file. I'm currently getting a 422 error and I've been receiving it for a while now. My question is: How do I receive that JSON error itself in Java so that I can see what the error is. All I'm seeing is a HttpResponseException and it doesn't give me anything else. Thanks for the time and help in advance.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mPath);
// Add your data
try
{
List nameValuePairs = new ArrayList(4);
httppost.setHeader("Authorization", Base64.encodeToString(new StringBuilder(bundleId).append(":").append(apiKey).toString().getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP));
nameValuePairs.add(new BasicNameValuePair("state", "CA"));
nameValuePairs.add(new BasicNameValuePair("city", "AndDev is Cool!"));
nameValuePairs.add(new BasicNameValuePair("body", "dsads is assrawstjljalsdfljasldflkasjdfjasldjflasjdflkjaslfggddsfgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfddjflaskjdfkasjdlfkjasldfkjalskdjfajasldfkasdlfjasljdflajsdfjasdjflaskjdflaksjdfljasldfkjasljdflajsasdlfkjasldfkjlas!"));
nameValuePairs.add(new BasicNameValuePair("title", "dsaghhhe fd!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
//HttpResponse response = httpclient.execute(httppost);
//int status = response.getStatusLine().getStatusCode();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
Log.v(TAG, "response: " + responseBody);
//JSONObject response = new JSONObject(responseBody);
int f = 0;
}
catch(HttpResponseException e)
{
Log.e(TAG, e.getLocalizedMessage());
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
you may send your parameters more conveniently by using predefined Json class as below:
String jsonParam = null;
try{
JSONObject param = new JSONObject();
param.put("state", "CA");
param.put("city", "AndDev is Cool!");
//and so on with other parameters
jsonParam = param.toString();
}
catch (Exception e) {
// TODO: handle exception
}
and set the post entity as:
if(jsonParam != null)
httppost.setEntity(new StringEntity(jsonParam, HTTP.UTF_8));
422 error says: Unprocessable Entity - The request was well-formed but was unable to be followed due to semantic errors
You got a problem with UrlEncodedFormEntity