How can I post in Android? - java

I was using Android API, to send some data using http POST method:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myapp.com/");
try {
List parameters = prepareHttpParameters();
HttpEntity entity = new UrlEncodedFormEntity(parameters);
httppost.setEntity(entity);
ResponseHandler responseHandler = new BasicResponseHandler();
response = httpclient.execute(httppost, responseHandler);
Toast.makeText(this, response, Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO: manage ClientProtocolException and IOException
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
and my parameters are prepared here:
List parameters = new ArrayList(2);
parameters.add(new BasicNameValuePair("usr", "foo" ));
parameters.add(new BasicNameValuePair("pwd", "bar" ));
return parameters;
But it seems to be wrong because I do not get any expected response.
I have tested the same request with same parameters using Curl and I get expected response.
Am I wrong with my code?
Thank you very much

I'd consider the UrlEncodedFormEntity constructor that takes an encoding as the second parameter. Otherwise, off the cuff, this looks OK. You might check on your server logs what you are receiving for these requests. You might also make sure your emulator has Internet connectivity (i.e., has two bars of signal strength), if you are using the emulator.
Here is the relevant portion of a sample app that uses HTTP POST (and a custom header) to update a user's status on identi.ca:
private String getCredentials() {
String u=user.getText().toString();
String p=password.getText().toString();
return(Base64.encodeBytes((u+":"+p).getBytes()));
}
private void updateStatus() {
try {
String s=status.getText().toString();
HttpPost post=new HttpPost("https://identi.ca/api/statuses/update.json");
post.addHeader("Authorization",
"Basic "+getCredentials());
List<NameValuePair> form=new ArrayList<NameValuePair>();
form.add(new BasicNameValuePair("status", s));
post.setEntity(new UrlEncodedFormEntity(form, HTTP.UTF_8));
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String responseBody=client.execute(post, responseHandler);
JSONObject response=new JSONObject(responseBody);
}
catch (Throwable t) {
Log.e("Patchy", "Exception in updateStatus()", t);
goBlooey(t);
}
}

Related

HTTP response being cached in Android client

I have following situation:
Sending http post (post data contains json string) request to my remote server.
Getting http post response from my server in json: {"result":true}
Disconnecting all internet connections in my tablet.
Repeating post request described in step 1.
Getting the same cached "response" - {"result":true} which I didn't expected to get... I don't want that my http client would cache any data. I expect to get null or something like this.
How to prevent http client caching data?
My service handler looks like this:
public String makeServiceCall(String url, int method,
List<NameValuePair> params, String requestAction) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
}
else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
// Toast.makeText(Globals.getContext(), "check your connection", Toast.LENGTH_SHORT).show();
}
return response;
}
I just noticed that response is a member variable. Why do you need a member variable to return this result. You're probably returning the same result on the 2nd try. Re-throw the exception that you catch instead and let the caller handle it.

How should client send json data to PHP

I have used php for server side and my client(A java program) sends a post request with json data as parameter. I am able to receive the data but the jsonData is no decoding. I am sending a valid JSON.
Below is my Client program.
public class ExampleHttpPost
{
public static void main(String args[]) throws ClientProtocolException, IOException
{
HttpPost httppost = new HttpPost("http://localhost/hello.php");
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
try {
parameters.add(new BasicNameValuePair("data", (new JSONObject("{\"imei\":\"imei1\"}")).toString()));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httppost.setEntity(new UrlEncodedFormEntity(parameters));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity resEntity = httpResponse.getEntity();
// Get the HTTP Status Code
int statusCode = httpResponse.getStatusLine().getStatusCode();
// Get the contents of the response
InputStream input = resEntity.getContent();
String responseBody = IOUtils.toString(input);
input.close();
// Print the response code and message body
System.out.println("HTTP Status Code: "+statusCode);
System.out.println(responseBody);
}
}
And my hello.php
<?php
$data = $_POST['data'];
var_dump($data);
$obj = json_decode($data);
if($obj==NULL){
echo "Decoding error";
}
echo $obj['imei'];
?>
Output :
HTTP Status Code: 200
string(20) "{\"imei\":\"imei1\"}"
Decoding error
It seems like your Java Application is adding slashes to the string or as suggested in the comments the PHP app is probably adding slashes to the quotes to avoid SQL injection
Try if you can get it to work by adding
$data = stripslashes($data);
Above the json_decode part

Why does converting this Python POST request to Java not work?

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));

httpclient.execute works but overloaded function throws exception

I'm writing an Android application. It sends a HTTPPost to a server and receives the answer, when I use :
public final HttpResponse execute (HttpUriRequest request)
it's ok,
but when I try to use:
public T execute (HttpUriRequest request, ResponseHandler<? extends T> responseHandler)
it throws ClientProtocolException
because of some reasons I wanna use the second function, what should I do? What is the exception for ?
here is the code that uses the first function :
HttpPost httppost = new HttpPost("http://foo.Com/GeneralControls/Service.asmx/Login");
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost) ;
and here is the code that uses the second function:
HttpPost httppost = new HttpPost("http://foo.Com/GeneralControls/Service.asmx/Login");
DefaultHttpClient httpclient = new DefaultHttpClient();
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String response = httpclient.execute(httppost , responseHandler) ;
throws ClientProtocolException.
See the below code is working fine for me
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE,
Util.cookieStore);
try {
HttpResponse response = httpclient.execute(httppost,
localContext);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But you are trying to pass ResponseHandler and it accepts httpContext
The problem was a protocol problem, the webservice was changing the Destination URL and it produced an Exception

httpclient redirect for newbies [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Httpclient 4, error 302. How to redirect?
I want to retrieve some information from my comcast account. Using examples on this site, I think I got pretty close. I am using firebug to see what to post, and I see that when I login I am being redirected. I don't understand how to follow the redirects. I have played with countless examples but just can't figure it out. I am new to programming and just not having any luck doing this. Here is my code. I make an initial login, then go to try to go to another URL which is where the redirects begin. Along the way, I see that I am acquiring lots of cookies, but not the important one s_lst.
HttpPost httpPost = new HttpPost("https://login.comcast.net/login");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("continue", "https://login.comcast.net/account"));
nvps.add(new BasicNameValuePair("deviceAuthn", "false"));
nvps.add(new BasicNameValuePair("forceAuthn", "true"));
nvps.add(new BasicNameValuePair("ipAddrAuthn", "false"));
nvps.add(new BasicNameValuePair("lang", "en"));
nvps.add(new BasicNameValuePair("passwd", "mypassword"));
nvps.add(new BasicNameValuePair("r", "comcast.net"));
nvps.add(new BasicNameValuePair("rm", "2"));
nvps.add(new BasicNameValuePair("s", "ccentral-cima"));
nvps.add(new BasicNameValuePair("user", "me"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
System.out.println("executing request " + httpPost.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpPost, responseHandler);
String cima = StringUtils.substringBetween(responseBody, "cima.ticket\" value=\"", "\">");
System.out.println(cima);
HttpPost httpPost2 = new HttpPost("https://customer.comcast.com/Secure/Home.aspx");
List <NameValuePair> nvps2 = new ArrayList <NameValuePair>();
nvps2.add(new BasicNameValuePair("cima.ticket", cima));
httpPost2.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8));
System.out.println("executing request " + httpPost2.getURI());
// Create a response handler
ResponseHandler<String> responseHandler2 = new BasicResponseHandler();
String responseBody2 = httpclient.execute(httpPost2, responseHandler2);
System.out.println(responseBody2);
Here's a sample adapted from the 'Response Handling' example here.
Your example is quite complicated - best to simplify your code while you figure out how to follow redirects (you can comment out the section I've highlighted to show the example failing to follow the redirect).
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.protocol.*;
public class ClientWithResponseHandler {
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
// Comment out from here (Using /* and */)...
httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
boolean isRedirect=false;
try {
isRedirect = super.isRedirected(request, response, context);
} catch (ProtocolException e) {
e.printStackTrace();
}
if (!isRedirect) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 301 || responseCode == 302) {
return true;
}
}
return false;
}
});
// ...to here and the request will fail with "HttpResponseException: Moved Permanently"
try {
HttpPost httpPost = new HttpPost("http://news.bbc.co.uk/");
System.out.println("executing request " + httpPost.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println(responseBody);
// Add your code here...
} finally {
// When HttpClient instance is no longer needed, shut down the connection
// manager to ensure immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}

Categories

Resources