how to pass arralylist in basic namevalue pairs in android - android

Hello Sir i want send list of data to php server i use following code is it correct or not please tell me
i try this code
ArrayList<String>list1=new ArrayList<String>();
for(int i=0;i<json.length();i++)
{
JSONObject e = json.getJSONObject(i);
list1.add(e.getString("menuname"));
}
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("menuname",list1.toString()));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.103/update.php");
// "http://192.168.1.12/addnotes.php");
//url+"Notes/addnotes.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Toast.makeText(getApplicationContext(),
"Saved Sucessfully", Toast.LENGTH_SHORT).show()
please see the above code is correct or not .. please tell me

i think you want to get content in String right than use this
String mResponseText = EntityUtils.toString(entity);
insetad of
is= entity.getContent();
may it helps you

Related

How to send Japanese characters using HttpPost

I'm trying to send Japanese characters to my API server but the characters sent were garbled and became ????. So I set the encoding to the entity using:
StringEntity stringEntity = new StringEntity(message, "UTF-8");
but the output became org.apache.http.entity.StringEntity#4316f850. I wonder if converting the stringEntity to string caused this since I want to send it in my server as String.
Here's how I used it:
public static String postSendMessage(String path, String message) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 10000); // Timeout limit
HttpPost httpPost = new HttpPost(SystemInfo.getApiUrl() + path);
List<NameValuePair> value = new ArrayList<NameValuePair>();
StringEntity stringEntity = new StringEntity(message, "UTF-8");
value.add(new BasicNameValuePair("message", stringEntity.toString())); //Here's where I converted the stringEntity to string
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
String result = convertStreamToString(is);
return result;
}
Where could I have gone wrong?
You don't need to use StringEntity.
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("message", message));
Instead, you have to pass a second argument for initializing `UrlEncodedFormEntity.
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value, "UTF-8");

Android POST JSON OBJECT - How to set $_POST Index

i have a JSONObject which i want to POST to a server.
Here is the Code:
JSONObject obj = new JSONObject();
for(int k = 0; k<len;k++){
obj.put("nachrichten_ids", params[k]);
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("xxxxx");
HttpEntity entity;
StringEntity s = new StringEntity(obj.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = s;
httpPost.setEntity(entity);
HttpResponse response;
response = httpClient.execute(httpPost);
By doing Log.i("TEST",obj) i get the JSON object:
{"nachrichten_ids":"[2144,2138]"}
That data is send to the server. But i cant access it:
There is no $_POST index. (PHP)
How to set a index, so that i can access the json object, like $_POST['nachrichten_ids'].
I had to work with that data then e.g with php json_decode()
Any idea ?
Thanks
Try putting your jSON object into a namevaluepair. The name of the pair you add is the name you should use when reading it on the web. For example here I will get Password by calling $_POST['Password'].
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Password", "My password"));
nameValuePairs.add(new BasicNameValuePair("Mail", "My mail"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
BasicHttpResponse response = (BasicHttpResponse) httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

What is the best way to send a name value pair to a server?

I've been trying this for the best part of two weeks now, and I am really stuck. Initially I had created a simple ObjectOutputStream client - server program - with the client being the Android app, but it does not work (it reads the connection but not the object).
So now I am confused as to what other approaches I might be able to take to carry out this simple task? Can anyone Help?
have you tried URLConnection using post method? :)
Or get method like:
String yourURL = "www.yourwebserver.com?value1=one&value2=two";
URL url = new URL(yourURL);
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
response = in.readLine();
you can try JSON stirng to send data. We have a lot of stuff available on how to work with JSON and also there are many api's. JSONSimple is the one I can suggest. Its really easy.
why don't you try this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
You can use this to post an Entity to server:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
postRequest.setEntity(entity);
try {
HttpResponse response = httpClient.execute(postRequest
);
String jsonString = EntityUtils.toString(response
.getEntity());
Log.v(ProgramConstants.TAG, "after uploading file "
+ jsonString);
return jsonString;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
An Entity can be name value pair:
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("key1", value1));
nvps.add(new BasicNameValuePair("key2", value2));
Entity entity=new UrlEncodedFormEntity(nvps, HTTP.UTF_8)
Or you can send an entity with bytearray.
Bitmap bitmapOrg=getBitmapResource();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
entity.addPart("file", new ByteArrayBody(data, "image/jpeg",
"file"));
If you want to post json to server:
Please check out this link How do I send JSon as BODY In a POST request to server from an Android application?
For serializing and deserializing java object, I recommend https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson
Really hope it can help you see an overview of sending data to server

Unable to authenticate services

i need to authenticate my services with username and passwor i have try this but not get sucess can you help me
when i print inlog cat i got ::
Update 3 ::
11-04 16:07:58.767: INFO/System.out(1531): Returned ======>>> <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">Server was unable to process request. ---> Data at the root level is invalid. Line 1, position 1.</soap:Text></soap:Reason><soap:Detail /></soap:Fault></soap:Body></soap:Envelope>
Code ::
DefaultHttpClient UserIDclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("username","password"));
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
httppost.setEntity(p_entity);
HttpResponse response = UserIDclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
Returned = EntityUtils.toString(resEntity);
System.out.println("ans is :: "+ Returned);
System.out.println("Returned ======>>> "+Returned);
1st Thing:
Check whether the "returned" string is null or not.
2nd Thing:
One thing i notice that you have written below lines for twice, what is the need to call execute() method before passing username and password:
HttpResponse response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
Returned = EntityUtils.toString(entity);
Instead your code should be:
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// Your DATA
nameValuePairs.add(new BasicNameValuePair("ID", "username"));
nameValuePairs.add(new BasicNameValuePair("Password", "password"));
response.setEntity(new UrlEncodedFormEntity(nameValuePairs,
HTTP.UTF_8));
HttpResponse response1 = httpclient.execute(post);
if(response1.getStatusLine().getStatusCode()==200)
{
HttpEntity resEntity = response1.getEntity();
System.out.println("=========> Response => "+iStream_to_String(resEntitiy.getContent()));
}
// You can get iStream_to_String from here.

Android HTTPRequest Cycle

I am trying to send JSON to my server and retrieve a JSON in return as a result.
Like sending in username and password and getting back token and other content.
This is what i am doing for the HTTP Request for sending. How do i now retrieve back the content in the same request ?
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("http://192.168.1.5/temp/test.php");
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("Name", jsonStr));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse res = client.execute(request);
String[] status_String=res.getStatusLine().toString().trim().split(" ");
//String hd=res.getFirstHeader("result").toString();
//System.out.println("Res=" + res);
Log.e("tag", ""+res.toString());
if(status_String[1].equals("200")){
isDataSent=true;
Let me add more in vvieux's answer:
res.getEntity().getContent()
will return you InputStream.
String returnData = EntityUtils.toString(res.getEntity());
You can use the HttpEntity
res.getEntity().getContent()

Categories

Resources