I want to send a http request to a url with Android.
I am an iOS developer and now trying to learn Android.
I used to send the JSON string in iOS like below
{"function":"login", "parameters": {"username": "nithin""password": "123456"}}
How can I send this in Android?
I tried List<NameValuePair> but can't find the proper solution.
Full code of what I tried -
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("function", "login"));
nameValuePairs.add(new BasicNameValuePair("username", "nithin"));
nameValuePairs.add(new BasicNameValuePair("password", "123456"));
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 think JsonStringer is easy and useful for you here..
Try this:
HttpPost request = new HttpPost(URL);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
JSONStringer vm;
try {
vm = new JSONStringer().object().key("function")
.value(login).key("parameters").object()
.key("username")
.value(nithin).key("password").value("123456")
.endObject().endObject();
StringEntity entity = new StringEntity(vm.toString());
request.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Related
I use this code in my app to post:
public void postData() {
// Create a new HttpClient and Post Header
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
}
}
my problem is that when I do 10 posts some time its slow and some times it's not recive answer from the server.
Their is a way to do a manager for the posts or some way to do it fater and to make sure that after this code run I know that it dose all it's needs to recive answer from the server?
Thanks
I am trying to send data from android smartphone to a restful webservice made in java using jersey library.
I saw the following answer on how to do it:
public void postData() {
// Create a new HttpClient and Post Header
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", "Hi"));
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
}
}
Although this seems about right i have a doubt in the nameValuePairs variable.
Particularly in this part:
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
If i have a webservice that has the following signature:
#POST
#Path("/post/location")
#Consumes(MediaType.APPLICATION_JSON)
public Response createLocation(Loc location)
what would be the "id" part in the nameValuePairs variable, it would be location or Loc?.
try this
//
String url = 'url_to_you_server_api.dev/postservice'
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
JSONObject params = new JSONObject();
params.put("id","id");
params.put("hi","hi");
StringEntity jsonEntity = new StringEntity( params.toString() );
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type","application/json");
request.setEntity(jsonEntity);
response = client.execute(request);
if you service receive a entity it might be a json or something not just key-value params that correspond to form-data.
I am working on a login service that logs a user in then after a successful login it posts again to a new script with a cookie that was given on the login to get more info. here is my login post:
#Override
protected Boolean doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://testsite.com/login");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", "john"));
nameValuePairs.add(new BasicNameValuePair("password", "test"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String TAG = "com.imtins.worryfree";
String responseAsText = EntityUtils.toString(response.getEntity());
Log.d(TAG, "Response from server: " + responseAsText.toString());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
Now from what ive read if I use the same hpptClient without starting a new one, when i do another post it will use the cookie that i recieved? where could I add a second post in my example or how would it look. Just getting started with android/Java so this is a little confusing for me.
Thanks.
You can use an HttpContext + CookieStore to keep track of cookie state between requests. I think something like this would work for you (untested):
#Override
protected Boolean doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpPost httppost = new HttpPost("http://testsite.com/login");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", "john"));
nameValuePairs.add(new BasicNameValuePair("password", "test"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost, localContext);
String TAG = "com.imtins.worryfree";
String responseAsText = EntityUtils.toString(response.getEntity());
Log.d(TAG, "Response from server: " + responseAsText.toString());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
And for your 2nd request, reuse the localContext variable:
// replace XXX below with correct URL
httppost = new HttpPost("http://testsite.com/XXXXXX");
try {
// set entities here ...
HttpResponse response = httpclient.execute(httppost, localContext);
String TAG = "com.imtins.worryfree";
String responseAsText = EntityUtils.toString(response.getEntity());
Log.d(TAG, "Response from server: " + responseAsText.toString());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
That's my code... is it possible to remove the urlencode?
I want to pass post parameters without urlencode them.
Thanks
public void postData() {
// Create a new HttpClient and Post Header
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", "Hi"));
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
}
}
You can try something like this
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
BasicHttpEntity filter = new BasicHttpEntity();
filter.setContent(new ByteArrayInputStream("Filter=id :EQUALS: 12345 :AND: stringdata :EQUALS: hi".getBytes("UTF-8")));
httppost.setEntity(filter);
Thanks
I have javascript code that i am trying to mimic in an android application:
Here is the javascript code:
text = '{"username":"Hello","password":"World"}';
x.open("POST", url);
x.setRequestHeader("Content-type", "application/json");
x.setRequestHeader("Content-length", text.length);
x.send(text);
and here is what i have so far for the android application(doesnt work):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json");
String text = "\"{\"username\":\"Hello\",\"password\":\"World\"}\"";
httppost.setHeader("Content-length",Integer.toString(text.length()));
httppost.setEntity(new StringEntity(text));
HttpResponse response = httpclient.execute(httppost);
when i try to debug this code on eclipse the emulater keeps running while the debugger hangs. Thanks!
Note: its hanging on httpclient.execute(httppost)
Here is the code I use for Android post requests:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("fullurl");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("parameter", "variable");
post.setEntity (new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
...and so on.
Try it out:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
JSONObject json = new JSONObject();
try{
json.put("username", "Hello");
json.put("password", "World");
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
catch(Exception e){
e.printStackTrace();
}
Did you mean to set your HttpPost path to just path. I think your hanging because you haven't given the HttpPost a valid URL. You'll need to modify this line:
HttpPost httppost = new HttpPost("path");
to something like
HttpPost httppost = new HttpPost("actual/url/path");
You have extra speech marks within the start and end of your text string compared to the JS version?
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(StringUrl);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println("rep => " + response);
} catch (IOException e) {
System.out.println(e);
}
}