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();
}
Related
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.
I'm trying to send a json file to remote server. If I try it, using this site:
https://www.hurl.it/ passing a json like this:
it works. But If I try it from my code, I have some trouble.
ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
JSONArray list1 = new JSONArray();
list1.add("12345678");
Map obj=new LinkedHashMap();
obj.put("company_id","1");
obj.put("phones", list1);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
nameValuePairs1.add(new BasicNameValuePair("json", obj.toString()));
try {
URL url = new URL("http://crm.pavlun.info/api/register");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.setEntity(new StringEntity(nameValuePairs1.toString(), "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
HttpResponse response = httpClient.execute(httpPost);
Log.e("r ", response.toString());
}catch(Exception e) {
e.printStackTrace();
}
This is my json example: I need to create something like this: "json":{"company_id":"1","phones":["555555"],"photo":"/files/clients_photos/tmp/484629825.JPG","name":"sdfsdfdsf","birthdate":"10.02.2014", "email":"sdf#sdf.ff"}
UPD:
I have the following error:
{"status":"error","message":"Customer data is empty!"}
Maybe something is wrong in my json.
UDP:
working code
ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
JSONObject joB = new JSONObject();
JSONArray list1 = new JSONArray();
list1.add("258963147");
Map obj=new LinkedHashMap();
obj.put("company_id","1");
obj.put("phones", list1);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
org.json.JSONObject jsonqwe;
try {
JSONParser operationLink = new JSONParser();
ArrayList<NameValuePair> postP = new ArrayList<NameValuePair>();
postP.add(new BasicNameValuePair("json", JSONValue.toJSONString(obj)));
jsonqwe = operationLink.makeHttpRequest("http://crm.pavlun.info/api/register", "POST", postP);
Log.e("sad", jsonqwe.toString());
}catch(Exception e) {
e.printStackTrace();
}
You're problem is that you're not building a JSON object, but using the map's toString() method, which won't give you a properly formatted JSON object.
Try JSONObject's constructor that takes a map as parameter. And than call toString() on the JSONObject.
Try yo change
Map obj=new LinkedHashMap();
to
JSONObject obj=new JSONObject();
you need to send a JSON value
A more suitable solution would be to build a JSONObject instead of the Map you're using. Something like this:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONArray phoneNumbers = new JSONArray();
phoneNumbers.add("12345678");
JSONObject obj=new JSONObject();
obj.put("company_id","1");
obj.put("phones", phoneNumbers);
obj.put("name","Alexy");
obj.put("birthdate","12.03.2014");
obj.put("email","nesalexy#mail.ru");
nameValuePairs.add(new BasicNameValuePair("json", obj.toString()));
try {
URL url = new URL("http://crm.pavlun.info/api/register");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.setEntity(new StringEntity(nameValuePairs.toString(), "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
HttpResponse response = httpClient.execute(httpPost);
Log.e("r ", response.toString());
}catch(Exception e) {
e.printStackTrace();
}
This line will return garbage (as far server is concerned)
nameValuePairs1.toString()
because an ArrayList does implement toString like you are expecting. You should be using JSONArray/JSONObject instead.
In the hurl site example one name valu pair is sent. To send name value pais your content type should be form url encoded. So change:
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
to
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
Maybe this will help:
httpPost.setHeader("ENCTYPE","multipart/form-data");
EDIT:
As others already stated do not use a Map but a JSONObject. Then change
httpPost.setEntity(new StringEntity(nameValuePairs1.toString()));
to:
String nameValuPairsText = nameValuePairs.toString();
nameValuPairsText = nameValuPairsText.substring(1, nameValuPairsText.length()-1);
httpPost.setEntity(new StringEntity(nameValuPairsText, "UTF-8"));
i have made an activity in android,in that i have made a multipart entity request using HttpPost,Now i am getting successfull respose also.but thing is i dont know how to get those data from response.i have tried number of links for parsing xml but with no luck.Please help me for this.how to get data from my xml respose.My code is as below:
login
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Consts.API_HOST + "/login");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("apiKey",
"JU7Jqt6X"));
nameValuePairs.add(new BasicNameValuePair("type", "xml"));
nameValuePairs.add(new BasicNameValuePair("email",
"yogesh#amarinfotech.com"));
nameValuePairs.add(new BasicNameValuePair("pwd", "123"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// xml response..!jigar...
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// end of res jigar...
System.out
.println("::::::::::::::::::::::::;;MY RESPONSE IN LOGIN ATIVITY::::::::::"
+ responseBody);
// making doc
Document doc = null;
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader sr = new StringReader(responseBody);
InputSource is = new InputSource(sr);
doc = builder.parse(is);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
} catch (Exception e) {
System.out
.println("::::::::::::::::::::::::::::MY exception in edit::::::::::::::::"
+ e.getMessage());
return null;
}
return null;
// Parsing Procedure......
Response
<?xml version="1.0" encoding="ISO-8859-1" ?>
<root>
<id>
8
</id>
<personal_title>
Mr.
</personal_title>
<first_name>
a
</first_name>
<middle_name>
b
</middle_name>
<last_name>
c
</last_name>
<email>
yogesh#amarinfotech.com
</email>
<password>
202cb962ac59075b964b07152d234b70
</password>
<mobile_number>
1234567890
</mobile_number>
<p_first_name>
</p_first_name>
<p_last_name>
</p_last_name>
<p_card_type>
</p_card_type>
<p_card_number>
</p_card_number>
<p_sec_code>
</p_sec_code>
<p_exp_month>
</p_exp_month>
<p_exp_year>
</p_exp_year>
<user_activation_key>
14164668001
</user_activation_key>
<varification>
1
</varification>
<send_mail>
0
</send_mail>
<status>
0
</status>
<register_date>
2014-11-20 23:04:14
</register_date>
<last_visit_date>
2014-11-20 23:04:14
</last_visit_date>
</root>
I got my answer by my way.Hello all for your responses but i got myy question solved by my way ,Actually all are telling me about different parsing but i want to know about the parsing from HTTP RESPONSE,So i have got my solution,here it is:
http://www.java2s.com/Code/Android/Development/getCharacterDataFromElement.htm
Thanks for this useful post.
String xml="<yourxml></yourxml>"
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/xml");
StringEntity entity = new StringEntity(xml);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
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
I need to create an HTTP POST request with parameters. I know there are many examples out there, I have tried using HTTPparams, NameValuePair etc but cant seem to get the correct format for the server.
Server Type: REST based API utilizing JSON for data transfer
Content-type: application/json
Accept: application/json
Content-length: 47
{"username":"abcd","password":"1234"}
I can pass these headers but I cant seem to pass these params "username","password". Here is my code:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username","abcd"));
pairs.add(new BasicNameValuePair("password","1234"));
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,"UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
I tried to debug, but cant see if entity is attached properly or not... What am I doing wrong?
Thanks in Advance.
Maaz
Try this:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
obj.put("username", "abcd");
obj.put("password", "1234");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
I'm not quite sure, from your description, but it would seem that your server expects a JSON content object instead of the data being encoded in the URL. Send something like this as the body of your post:
{"username":"abcd","password":"1234"}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.mymi5.net/API/auth/login");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username","abcd"));
pairs.add(new BasicNameValuePair("password","1234"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse response = client.execute(post);
just try this coz it works perfect for me when i am trying to HTTP post.
this will probably work for you.
assuming you already have the json object.
NOTE: (1)in the server you need to handle th request as utf-8 (also in the DB).
#SuppressWarnings("unchecked")
private static HttpResponse executePostRequest(JSONObject jsonData, String url) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
try {
httpost.setEntity(new ByteArrayEntity(jsonData.toString().getBytes("UTF8")));
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json;charset=UTF-8");
httpost.setHeader("Accept-Charset", "utf-8");
HttpResponse httpResponse = httpclient.execute(httpost);
return httpResponse;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
then in the client handle the server response like this:
String responseBody = EntityUtils
.toString(response.getEntity(), "UTF-8");