sending json object to HTTP server in android - android

I am sending a JSON object to a HTTP Server by using the following code.
The main thing is that I have to send Boolean values also.
public void getServerData() throws JSONException, ClientProtocolException, IOException {
ArrayList<String> stringData = new ArrayList<String>();
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://consulting.for-the.biz/TicketMasterDev/TicketService.svc/SaveCustomer");
JSONObject json = new JSONObject();
json.put("AlertEmail",true);
json.put("APIKey","abc123456789");
json.put("Id",0);
json.put("Phone",number.getText().toString());
json.put("Name",name.getText().toString());
json.put("Email",email.getText().toString());
json.put("AlertPhone",false);
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
String response = httpClient.execute(postMethod,resonseHandler);
Log.e("response :", response);
}
but its showing the exception in the line
String response = httpClient.execute(postMethod,resonseHandler);
as
org.apache.http.client.HttpResponseException: Bad Request
can any one help me.

The Bad Request is the server saying that it doesn't like something in your POST.
The only obvious problem that I can see is that you're not telling the server that you're sending it JSON, so you may need to set a Content-Type header to indicate that the body is application/json:
postMethod.setHeader( "Content-Type", "application/json" );
If that doesn't work, you may need to look at the server logs to see why it doesn't like your POST.
If you don't have direct access to the server logs, then you need to liaise with the owner of the server to try and debug things. It could be that the format of your JSON is slightly wrong, there's a required field missing, or some other such problem.
If you can't get access use to the owner of the server, the you could try using a packet sniffer, such as WireShark, to capture packets both from your app, and from a successful POST and compare the two to try and work out what is different. This can be a little bit like finding a needle in a haystack though, particularly for large bodies.
If you can't get an example of a successful POST, then you're pretty well stuffed, as you have no point of reference.

This may be non-technical, but
String response = httpClient.execute(postMethod,-->resonseHandler);
There is a spelling mistake in variable name here, use responseHandler(defined above)

Related

Sending POST json from Android and receiving on Django

I am trying to get an android app to interact with a server in Django.
The app is trying to POST "json" data to Django. However, I am unable to receive the object on the Django end.
The value of request.POST is <QueryDict: {}> although the data sent isn't blank. Following is the code snippet for POST request from android.
public static String POST(String url,JSONObject obj){
InputStream inputStream = null;
String result = "";
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = obj.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type","application/json");
HttpResponse httpResponse = httpClient.execute((HttpUriRequest)httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream!=null){
result = convertInputStreamToString(inputStream);
}else{
result = "Did not work!";
}
}catch(Exception e){
}
return result;
}
EDIT:
Earlier, I was getting CSRF error and handled it this way (I haven't worked with Django enough to know if this is correct way to handle CSRF error)
#csrf_exempt
def search(request):
logger.debug(request.POST)
"""Code for JSON object processing"""
Any help with rectifying the problem would be highly appreciated.
OK I'm not very fluent in java but it seems to me that your request is well formed.
I think the issue is that you are sending the data as a json string instead of as if it was a raw form. When you do it this way, the data is not displayed in request.POST but in request.body as what it is: a json string, not form-like data.
So I think you have to take one of these ways:
send the data from the Android app as a form (not json-like). This way you'll see it in request.POST or
translate request.body into a dict and work with it instead of request.POST
Hope this helps! :)

passing JSON object in URL of RESTFUL Web service in Android?

I am working with JSON Restful web serivces where I have to pass JSON object in the Service URL. I have created the JSON object successfully but getting exception when my URL created the HTTP connection with the SERVER.
Below I have mention my URL:
http://72.5.167.50:8084/UpdateProfileInfo?{"ProfileEditId":"917","ContactsEmail":[{"Email":"dsfs","ContactId":""}],"ContactsPhone":[{"CountryId":"+1","Type":"2","Phone":"345345"}],"ProfileId":"290","LastName":"demo","GroupId":"1212","Title":"sdf","City":"dsf","TemplateId":"1212","State":"dsf","AuthCode":"9bcc6f63-2050-4c5b-ba44-b8103fbc377a","Address":"sdf","FirstName":"demo","ContactId":"","Zip":"23","Company":"tv"}
Getting java.lang.IllegalArgumentException: Illegal character in query in code :
int TIMEOUT_MILLISEC = 100000; // 1000 milisec = 1 seconds
int SOCKET_TIMEOUT_MILISEC = 120000; // 2 minutes
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT_MILISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost(url);
HttpResponse response = client.execute(request);
responseString = request(response);
Please suggest me If I am doing something wrong with my URL.
*EDITED:*Tried with a key still getting Exeception:
http://72.5.167.50:8084/UpdateProfileInfo?profileinof={"ProfileEditId":"917","ContactsEmail":[{"Email":"sdf","ContactId":""}],"ContactsPhone":[{"CountryId":"+1","Type":"2","Phone":"345345345"}],"ProfileId":"290","LastName":"demo","GroupId":"1212","Title":"dsf","City":"dsf","TemplateId":"1212","State":"dsf","AuthCode":"d968273a-0110-461b-8ecf-3f9c456d17ac","Address":"dsf","FirstName":"demo","ContactId":"","Zip":"23","Company":"tv"}
There is different format of HTTP request that we needed to make for this kind of REQUEST.
I have mention my code below for this.
public JSONObject getJSONObject(){
return jsonObj;
}
ABove method returns me a JSON String which is passed in the below method.
public static HttpResponse makeRequest(String url) throws Exception
{
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost httpost = new HttpPost(url);
//convert parameters into JSON object
JSONObject holder = getJSONObject();
//passes the results to a string builder/entity
StringEntity se = new StringEntity(holder.toString());
//sets the post request as the resulting string
httpost.setEntity(se);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
return httpclient.execute(httpost, responseHandler);
}
Stack post helped me for doing this task...!!!
The IP is not correct.
IP is formed with 4 bytes. Every byte is a value from 0 to 255, can't be 7 thousand.
http://7232.25.1617.50:1084
Edit: Okay, you edited your question. You're sending a JSON as parameter. But this parameter has no "key".
Should be:
/UpdateProfileInfo?info={"ProfileEditId":"917",[.......]
Edit: I think this should be like this:
/UpdateProfileInfo?info="{'ProfileEditId':'917',[.......]}"
Notice that the value is surrounded by ", and the inner " are replaced now by '
Probably the issue is that you are trying to POST a JSON object as an url param.
If it really has to be an url param, that it has to be urlencoded.
If it rather should be a normal POST request, I's suggest to use a high level helper:
new RESTClient2(ctx).post("http://72.5.167.50:8084", jsonObject);
I can see a need to work with POJOs , converting them to JSON strings and conveying that string info over HTTP. There are lots of good android/java/apache/volley type libs that permit that.
However, i do not understand, in fact i disagree with your requirement to use GET and the URL parms for transport of your JSON string?
Its really easy to do the following:
POJO -> to JSON -> toString -> to http.string.entity -> POST
Why not re-examine your architecture and consider using POST not GET.
Then its easy , 2 step:
see example "request.setEntity( ... "
your code will look like this:
httpPost.setEntity(new StringEntity(pojo.toJSON().toString()));

Why Is JSON request returning as XML?

I'm a noob to android and I'm trying to parse a JSON from this link: "http://services.packetizer.com/spotprices/?f=json". However, when I send my request to parse it, i receive an error saying..." Error parsing data org.json.JSONException: Value xml of type java.lang.String cannot be converted to JSONObject". This is baffling to say the least because the link is obviously a JSON. Any help solving this is greatly appreciated.
My Code:
JSONObject json = JSONfunctions.getJSONfromURL("http://services.packetizer.com/spotprices/?f=json");
if(json==null){
//Do Nothing
}else{
String usdgold = json.getString("gold");
livespotgold = Double.parseDouble(usdgold);
storedspotgold=livespotgold;
Log.e("Spot Gold Packetizer", String.valueOf(livespotgold));
String usdsilver = json.getString("silver");
livespotsilver = Double.parseDouble(usdsilver);
storedspotsilver=livespotsilver;
Log.e("Spot Silver Packetizer", String.valueOf(livespotsilver));
haveSpot = true;
}
I assume you're using the JSONfunctions class from here or a modified version of it (as you're receiving a JSONObject and not a JSONArray).
Note that that code sends an HTTP POST. This endpoint is returning XML when you send it a POST. You need to change the code to send an HTTP GET:
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);

I cannot seem to find out if this webservice is getting the JSON object sent from Android

I have a android application which sends JSON information to a webservice for it to validate the information. I am using Kate as an editor for the webservice. The concept of JSON and php webservices is new to me. I normally code in java.
JSONObject jsonObject = new JSONObject();
String userID = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(loginURI);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams,10000);
try {
jsonObject.put("username", username);
Log.i("username", jsonObject.toString());
jsonObject.put("password", password);
Log.i("password", jsonObject.toString());
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
userID = EntityUtils.toString(httpResponse.getEntity());
Log.i("Read from server", userID);
}
}catch (IOException e){
Log.e("Login_Issue", e.toString());
}catch (JSONException e) {
e.printStackTrace();
}
return userID;
}
I found the StringEntity code online and thought it will work. I do not understand the purpose of the StringEntity for the HttpPost.
This is my webservice written in php.
include('dbconnect.php');
$tablename = 'users';
//username and password sent from android
$username=$_POST['myusername'];
$password=$_POST['mypassword'];
//protecting mysql injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
#$array = array($username,$password);
$sql = "SELECT first_name FROM $tablename WHERE u_username='$username' AND u_password=MD5('$password')";
//Querying the database
$result=mysql_query($sql);
if(!$result){
die(mysql_error();
}
//If found, number of rows must be 1
if((mysql_num_rows($result))==1){
//creating session
session_register("$username");
session_register("$password");
print true;
}else{
print false;
}
mysql_close();
I am not quite sure if the 'username' and the 'password' is being sent correctly from the android app to the webservice. How can I verify this? And is the webservice and the java code well-written to send the information in JSON?
When I go the webservice on the browser, I get the following error:
Parse error: parse error in E:\wamp\www\mobile.dcl.mu\webserver\login.php on line 24
Thank you in advance.
You try to bite off too much. It should be, like, 6 different questions (or just pay someone to write the scripts for you, or spend some time learning the technologies in isolation). Two first things to fix:
fix the parse error! it is as if you had a Java source that does not compile. The error is that you forgot the closing paren after die (mysql_error();
no, it will not work anyway. You send the data in the body as application/json, and you try to read it as url-encoded form. Decide which you want, ask for help on that.
remove the stripslashes. It does not add any security and will cause errors if anyone is using a slash in her password. Unless you have magic_quotes on, which you should not.
Since you made the three very basic mistakes so early, I am practically sure that there is much, much more to fix. Other than rewriting the whole thing for you or sending some general links on PHP programming and web application programming - I see no more way to help you. If you manage to split the problem, test things in isolation and ask more questions, there might be hope.
UPDATE
If you decide to standardize around JSON, the general pattern in your PHP files will be:
// get the body of the HTTP request (that's the "http entity")
$body = file_get_contents('php://input');
// translate JSON into ordinary PHP array:
$entity = json_decode($test, true);
// Now you can read parts of it as if you read an array;
// the data may be nested and will mirror exactly your JSONObject:
$username=$entity['myusername'];
$password=$entity['mypassword'];
[yes, that's me begging for an upvote :-)]
[and I think there is more problems in your Java code, but one thing at a time]

Send JSON data to compojure server from android

I'm trying to send some json data from Android to a clojure/compojure server
However I can't seem to able to properly send or receive the data, and I'm not quite sure if the problem lies with Android or compojure.
Here is the java code
String PATH = "http://localhost:8080/get_position";
DefaultHttpClient mClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(PATH);
HttpResponse response;
httpget.getParams().setParameter("measurements", measurements.toString());
response = mClient.execute(httpget);
HttpEntity entity = response.getEntity();
Where mesurements is the JSON object.
And the main compojure code for handling the routing
(defroutes main-routes
(POST "/get_position" {params :params}
(emit-json (find-location (:results (read-json (:measurements params))))))
(route/not-found "Page not found"))
The request is properly received, but I get an error that params is nil
java.lang.IllegalArgumentException: No implementation of method: :read-json-from of protocol: #'clojure.data.json/Read-JSON-From found for class: nil
Does anyone see a problem with this code or knows the correct way to do this?
The params map has strings as keys, I believe, not keywords.
I recommend using ring-json-params.

Categories

Resources