This question already has answers here:
HTTP POST using JSON in Java
(12 answers)
Sending a JSON HTTP POST request from Android
(2 answers)
Closed 5 years ago.
hi im new to AsyncTask and i need to send data to API server. im doing the connection and im stuck here. i read about the AsyncTask and this is the code that i've seen. first thing is if i determine if the device is connected, it will send data on the URL given, else. it will send thru SMS
public class SendData extends AsyncTask <String, Void, Boolean> {
DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
Date date = new Date();
String datefinal = dateFormat.format(date).toString();
String url = "http://192.168.1.212/mobile_alerts_api.php?location=&msg=&datetime=&id=";
#Override
protected Boolean doInBackground(String... urls) {
try{
HttpGet httppost = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
}
}
Use:
HttpPost httppost = new HttpPost(url);
instead of
HttpGet httppost = new HttpGet(url);
Get is used to get data from the server. Post is used to send data to the server
String json=yourJsonData;
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Content-type", "application/json");
Then execute the httppost in your async task class
Related
I'm trying to convert this Python code using the Python Requests HTTP library into Java code (for Android).
import requests
payload = {"attr[val1]":123,
"attr[val2]":456,
"time":0,
"name":"Foo","surname":"Bar"}
r = requests.post("http://jakiro.herokuapp.com/api", data=payload)
r.status_code
r.text
This is what I've done so far:
protected void sendJson() {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
Log.v("SOMETHING_NAME3", "Creating POST");
HttpPost post = new HttpPost("http://jakiro.herokuapp.com/api");
json.put(MessageAttribute.SURNAME, "Bar");
json.put(MessageAttribute.VAL1, 123);
json.put(MessageAttribute.VAL2, 456);
json.put(MessageAttribute.name, "Foo");
json.put(MessageAttribute.TIME, 0);
StringEntity se = new StringEntity( json.toString() );
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
String foo = convertStreamToString(in);
Log.v("SOMETHING_NAME2", foo); // Gives me "Bad request"
}
} catch(Exception e) {
e.printStackTrace();
Log.v("SOMETHING_NAME", "Cannot Establish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
I've checked the response with response.getStatusLine().getStatusCode() and I get back a 400 from the server. The Python code works fine, but in Java on an Android device it doesn't. I can't see to figure out why though.
#Blender's link was the correct solution at the link: How to use parameters with HttpPost
The correct way to url-encode was to create BasicNameValuePairs and encode that as such:
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
Hi I want to send a json object to a web service , I have tried almost everything without success. When the webservice recives the data it returns "eureka" , so I want to be able to see the response too.
public void sendData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://pruebaproyectosmi.azurewebsites.net/home/Insert?data=");
try {
httppost.setEntity(new UrlEncodedFormEntity(json));
// 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
}
}
private void SendBookingData(final String SendCustomerId,final String SendCustomerName, final String BookingDate,
final String BookingTime, final String SendNetAmount,final String SendTotalAmount, final String SendTotalQuantity,
final String SendDeliveryDate, final String GetBranchId,final String Senduserid,final String Sendratelistid) {
HttpClient client = new DefaultHttpClient();
JSONObject json = new JSONObject();
try {
String SendBookingURL= "your url";
HttpPost post = new HttpPost(SendBookingURL);
HttpResponse response;
json.put("GetcustomerName", SendCustomerName);
json.put("GetBookingDate",BookingDate);
json.put("GetTotalCost", SendTotalAmount);
json.put("GetNetAmount", SendNetAmount);
json.put("GetTotalQuantity",SendTotalQuantity );
json.put("GetCustomerId", SendCustomerId);
json.put("GetDeliveryDate", SendDeliveryDate);
json.put("GetBookingtime", BookingTime);
json.put("GetBranchId", GetBranchId);
json.put("GetUserId", Senduserid);
json.put("GetRateListId", Sendratelistid);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
try {
response = client.execute(post);
HttpEntity entity = response.getEntity();
if(entity != null) {
ResponseSummaryTable = EntityUtils.toString(entity);
System.out.println("body" + ResponseSummaryTable);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
catch(Exception e){
e.printStackTrace();
}
}
Send string entity instead
CODE:
HttpClient client = new DefaultHttpClient();
HttpUriRequest request;
request = new HttpPost(<-URL->);
StringEntity entity = new StringEntity(<-Your JSON string->);
((HttpPost) request).setEntity(entity);
((HttpPost) request).setHeader("Content-Type",
"application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
This code will send json as string entity to server and receives HttpEntity as response
In my application, the User can upload images to a PHP server, the iOS version is working 100%, the Android version used for this tutorial to upload image:
tutorial example
And the function I'm using is this:
public static String sendPost(String url, String imagePath)
throws IOException, ClientProtocolException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(url);
File file = new File(imagePath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
//Log.e("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
//Log.e(""+response.getStatusLine());
if (resEntity != null) {
//Log.e(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
return response.toString();
}
return response.toString(); get it in org.apache.http.message.BasicHttpResponse # 406dc148
But the return of the web service is the URL where the image was saved, I need to have a string in the return of the PHP server, rather than the return I mentioned above how can I have it?
I wanted something like this (HttpURLConnection):
HttpURLConnection conn;
...
String response= "";
Scanner inStream = new Scanner(conn.getInputStream());
while(inStream.hasNextLine())
response+=(inStream.nextLine());
Log.e("resp", response);
After one hour onsegui trying to get the response from the Web service as follows:
...
byte [] responseBody = httppost.getMethod().getBytes();
Log.e("RESPONSE BODY",""+(new String(responseBody)));
...
If you want the content returned by the HTTP server, you shouldn't do this:
if (resEntity != null) {
resEntity.consumeContent();
}
... because that says "throw away the content".
Try this if the response is of type String
ResponseHandler<String> responseHandler = new BasicResponseHandler();
HttpResponse httpResponse = httpClient.execute(post, new BasicHttpContext()); // new BasicHttpContext() not necessary
// verify connection response status using httpResponse.getStatusLine().getStatusCode() then
String response = responseHandler.handleResponse(httpResponse);
if(response != mull){
Log.e("Response : "+response);
}else{
// Handle exception
}
return response;
I am having a strange problem while using Apache HttpClient in an Android app.
My app needs to Login to a website and get some data and then logout.
My current code looks like this:
public class BlueClient {
private String hostUrl;
private DefaultHttpClient client;
private HttpContext localContext;
public BlueClient(String hostUrl,DefaultHttpClient httpClient,HttpContext localContext) {
this.hostUrl = hostUrl;
this.client = httpClient;
this.localContext = localContext;
}
public boolean doLogin(String userName,String password){
String url = getHostUrl()+"do_login";//loggin will set a session cookie
HttpPost post = new HttpPost(url);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",userName));
nameValuePairs.add(new BasicNameValuePair("password",password));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post,localContext);
//ok now if response is ok then return true
} catch (Exception e) {
}
return false;
}
public MyStuff getMyStuff(){
String url = getHostUrl()+"/getMyStuff/"; //this url requires authentication. the sesion cookie should do that
HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get,localContext);
//ok get my stuff from response and return
} catch (Exception e) {
}
return null;
}
public boolean doLogout(){
String url = getHostUrl()+"do_logout";//it clears the cookie so the session is invalidated
HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get,localContext);
//ok the cookie is cleared
}
} catch (Exception e) {
}
return false;
}
}
And when i call these function i do like this. It works in emulator but not in device
HttpContext context = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
context.setAttribute(ClientContext.COOKIE_STORE,cookieStore);
DefaultHttpClient httpClient = new DefaultHttpClient();
BlueClient myClient = new BlueClient("http://myHost.com/",httpClient,context);
myClient.doLogin("user","pass");
// it should've printed the cookies set by the server but i get nothing here !
D.log(context.getAttribute(ClientContext.COOKIE_STORE));
// as this is another subsequesnt request it shoud carry the cookies back to the server but as the cookies are not set this function gives me nothig :-(
myClient.getMyStuff();
myClient.doLogout();
Can anyone please shed some light on this. Why its not working in the device?
Ah I finally found the problem!
My server runs on CodeIgniter. And CodeIgniter set the expiry date of the session cookie (ci_session) as Netscape cookie draft compliant. And the format is EEE, dd-MMM-yy HH:mm:ss zzz and Default CookiePoicy used by HttpClient is RFC_2109. So when the httpClient tries to parse the cookie data it fails on parsing the expiry date. I had to explicitly set the Cookie Policy and date format.
So my final code looks like this:
BasicHttpParams params = new BasicHttpParams();
String[] dateFormats = {"EEE, dd-MMM-yy HH:mm:ss zzz"};
params.setParameter(CookieSpecPNames.DATE_PATTERNS,Arrays.asList(dateFormats));
DefaultHttpClient httpClient = new DefaultHttpClient(params);
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.NETSCAPE);//explicitly set the cookie policy
HttpContext context = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
context.setAttribute(ClientContext.COOKIE_STORE,cookieStore);
BlueClient myClient = new BlueClient("http://myHost.com/",httpClient,context);
myClient.doLogin("user","pass");
myClient.getMyStuff();//now i get my stuff !
myClient.doLogout();
Hope it saves someone's time :)
For example if we need to send content which is in this format , how do we do it
{"name1":[{"name11":"value11"},{"name11":"value12"},{"name11":"value13"}],"name2":value2}
I know how to set the basic kind
{"name1":"value1","name2":value2}
NameValuePair[] nameValuePairs = new NameValuePair[2];
nameValuePairs[0]= new BasicNameValuePair("name1", "value1");
nameValuePairs[1] = new BasicNameValuePair("name2", value2);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
How can we achieve nesting
Please see this question as it has a couple of answers that should help you. Here is a brief snippet from the answers code:
HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);
The other answer says you can do something like this:
protected void sendJson(final String email, final String pwd) {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try{
HttpPost post = new HttpPost(URL);
json.put("email", email);
json.put("password", pwd);
StringEntity se = new StringEntity( "JSON: " + json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
catch(Exception e){
e.printStackTrace();
createDialog("Error", "Cannot Estabilish Connection");
}
}