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
Related
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.
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));
I am using Play and Faye on my Server. Play is used for API calls, while Faye is used for communication with the clients.
So, I have this method in the server:
public static Result broadcast(String channel, String message)
{
try
{
FayeClient faye = new FayeClient("localhost");
int code = faye.send(channel, message);
// print the code (prints 200).
return ok("Hello"); <------------ This is what we care about.
}
catch(Exception e)
{
return ok("false");
}
}
this is the code on the client, which is an android phone.
(it's the HTTP post method, which sends something to the server and gets a response back
The problem is, I can't print the message of the response.
public static String post(String url, List<BasicNameValuePair> params)
{
HttpClient httpclient = new DefaultHttpClient();
String result = "";
// Prepare a request object
HttpPost httpPost;
httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
try
{
for (NameValuePair pair : params)
obj.put(pair.getName(), pair.getValue());
}
catch (JSONException e)
{
return e.getMessage();
}
// Add your data
try
{
httpPost.setEntity(new StringEntity(obj.toString(), "UTF-8"));
}
catch (UnsupportedEncodingException e)
{
return e.getMessage();
}
HttpResponse httpResponse;
try
{
httpResponse = httpclient.execute(httpPost);
// Get hold of the response entity
HttpEntity entity = httpResponse.getEntity();
String str = EntityUtils.toString(entity);
Log.e("RestClient", "result = \"" + str + "\""); // hello should be printed here??
}
catch(Exception e)
{
// ...
}
The problem is that in logcat, what is printed is [result = ""]. Am I doing something wrong?
Thank you.
Use a tool such as Fiddler and see what the HTTP response contains.
I need a simple code example of sending http post request with post parameters that I get from form inputs.
I have found Apache HTTPClient, it has very reach API and lots of sophisticated examples, but I couldn't find a simple example of sending http post request with input parameters and getting text response.
Update: I'm interested in Apache HTTPClient v.4.x, as 3.x is deprecated.
Here's the sample code for Http POST, using Apache HTTPClient API.
import java.io.InputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
public class PostExample {
public static void main(String[] args){
String url = "http://www.google.com";
InputStream in = null;
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
//Add any parameter if u want to send it with Post req.
method.addParameter("p", "apple");
int statusCode = client.executeMethod(method);
if (statusCode != -1) {
in = method.getResponseBodyAsStream();
}
System.out.println(in);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I pulled this code from an Android project by Andrew Gertig that I have used in my application. It allows you to do an HTTPost. If I had time, I would create an POJO example, but hopefully, you can dissect the code and find what you need.
Arshak
https://github.com/AndrewGertig/RubyDroid/blob/master/src/com/gertig/rubydroid/AddEventView.java
private void postEvents()
{
DefaultHttpClient client = new DefaultHttpClient();
/** FOR LOCAL DEV HttpPost post = new HttpPost("http://192.168.0.186:3000/events"); //works with and without "/create" on the end */
HttpPost post = new HttpPost("http://cold-leaf-59.heroku.com/myevents");
JSONObject holder = new JSONObject();
JSONObject eventObj = new JSONObject();
Double budgetVal = 99.9;
budgetVal = Double.parseDouble(eventBudgetView.getText().toString());
try {
eventObj.put("budget", budgetVal);
eventObj.put("name", eventNameView.getText().toString());
holder.put("myevent", eventObj);
Log.e("Event JSON", "Event JSON = "+ holder.toString());
StringEntity se = new StringEntity(holder.toString());
post.setEntity(se);
post.setHeader("Content-Type","application/json");
} catch (UnsupportedEncodingException e) {
Log.e("Error",""+e);
e.printStackTrace();
} catch (JSONException js) {
js.printStackTrace();
}
HttpResponse response = null;
try {
response = client.execute(post);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol",""+e);
} catch (IOException e) {
e.printStackTrace();
Log.e("IO",""+e);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
Log.e("IO E",""+e);
e.printStackTrace();
}
}
Toast.makeText(this, "Your post was successfully uploaded", Toast.LENGTH_LONG).show();
}
HTTP POST request example using Apache HttpClient v.4.x
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("param1", param1Value, ContentType.TEXT_PLAIN);
builder.addTextBody("param2", param2Value, ContentType.TEXT_PLAIN);
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
HttpResponse response = httpClient.execute(httpMethod);
http://httpunit.sourceforge.net/doc/cookbook.html
use PostMethodWebRequest and setParameter method
shows a very simple exapmle where you do post from Html page, servlet processes it and sends a text response..
http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/servlet.html
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);
}
}