JSONObject sent to .net service via HttpPost is recieving null JSONObject - java

I need to consume a json webservice method which accepts stringified jsonObject as a parameter,
This is how i am making JSONObject
btnRegister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
jsonObjSend = new JSONObject();
try{
jsonObjSend.put("FirstName", firstname.getText().toString());
jsonObjSend.put("LastName", lastname.getText().toString());
jsonObjSend.put("EmaillId", emailid.getText().toString());
jsonObjSend.put("Password", password.getText().toString());
jsonObjSend.put("MobileNumber", mobilenumber.getText().toString());
// jsonObjSend.put("Login_RememberMe", "true");
// JSONObject header = new JSONObject();
// header.put("deviceType","Android"); // Device type
// header.put("deviceVersion","2.0"); // Device OS version
// header.put("language", "es-es"); // Language of the Android client
// jsonObjSend.put("header", header);
}catch (JSONException e) {
e.printStackTrace();
}
new sendjsonObect().execute(URL);
}
});
}
public class sendjsonObect extends AsyncTask {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String jsonObjRecv = HttpClient.SendHttpPost(params[0],jsonObjSend);
Log.d("jsonObjSend",""+jsonObjSend);
Log.d("JsonObjRecv",""+jsonObjRecv);
return jsonObjRecv.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(Registration.this, result,Toast.LENGTH_LONG ).show();
Log.d("Result", ""+result);
}
}
This is the method where i am making the request call
public static String SendHttpPost(String URL, JSONObject jsonData) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se=null;
try {
se = new StringEntity(jsonData.toString(),HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
se.setContentType("application/json");
se.setContentEncoding("UTF-8");
// Set HTTP parameters
httpPostRequest.setEntity(se);
Log.d("Test", ""+se);
// httpPostRequest.setHeader("Accept", "application/json");
// httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
// Transform the String into a JSONObject
// JSONObject jsonObjRecv = new JSONObject(resultString);
//// Raw DEBUG output of our received JSON object:
// Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return resultString;
}
}
catch (Exception e)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
e.printStackTrace();
}
return null;
}
The JSONObject received at service side is showing as null.
What is the mistake i am doing?.

did you try application/x-www-form-urlencoded as content type.
httpPostRequest.addHeader("content-type", "application/x-www-form-urlencoded");

Related

POST JSON data to server

I am working on POST JSON data to server. It is working fine with a tutorial this link but it is not working with this with some of the required data changes. Is there anything related to Javaservlet and PHP links , as the first link is designed using Javasevlet and the other is in PHP ?
public static String POST(String url)
{
InputStream inputStream = null;
String result = "";
try {
org.apache.http.client.HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost(url);
String json = "";
JSONObject jsonObject=new JSONObject();
/*JSONArray jsonArray=jsonObject.getJSONArray("object");
JSONObject jsonObject2=jsonArray.getJSONObject(10);*/
jsonObject.putOpt("id",2);
jsonObject.putOpt("address","myaddress");
json=jsonObject.toString();
StringEntity se=new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse=httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// person = new PersonLocator();
// person.setAddresS(myLocationText.getText().toString());
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
Thanks for the help in advance

Not getting response of a webservice in android code

I am working on an application in that i have developed ios code for making a webservice call and it is giving me response successfully,The same webservice call when i am trying to call in android it is not working it is not giving me response,I am posting my both code,Can anybody help me to figure it?
ios code
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#",k_SERVER_BASE_ADDRESS,service_name]];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
[request setValue:[NSString stringWithFormat:#"%#",k_CONTENT_TYPE] forHTTPHeaderField:#"Content-Type"];
// 3
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:[NSString stringWithFormat:#"%#",k_USER_NAME] forKey:#"APIUserName"];
[dictionary setObject:[NSString stringWithFormat:#"%#",k_PASSWORD] forKey:#"Password"];
NSLog(#"%#",dictionary);
NSError *error = nil;
NSData *data_prm = [NSJSONSerialization dataWithJSONObject:dictionary
options:kNilOptions error:&error];
NSLog(#"%#",[[NSString alloc] initWithData:data_prm encoding:NSUTF8StringEncoding]);
if (!error) {
// 4
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:data_prm completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here..
NSLog(#"this is data : %#",data);
Android Code
public class GETCONTESTANTS extends AsyncTask<Void, Void, Void> {
StringEntity se;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(StartActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
// stateList.clear();
}
#Override
protected Void doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.fansplay.com/wsfptb20/FBS.svc/GetContestants");
String json = "";
try {
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("APIUserName", "AFBK8#DL4EJMd6");
jsonObject.accumulate("country","8GB4HE1C-EFSD-4L17-VY2D-A27OC8C52F6M");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
se = new StringEntity(json);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
In above codes "iOS code" is working fine and "android code" is not working. Can anyone please help me?
try this snippet of code may be helpful
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
String url="http://www.fansplay.com/wsfptb20/FBS.svc/GetContestants";
public JSONParser(){
}
public JSONObject makeHttpRequest(String url){
JSONObject jo = null;
jo = new JSONObject();
try {
jo.accumulate("APIUserName", "AFBK8#DL4EJMd6");
jo.accumulate("country","8GB4HE1C-EFSD-4L17-VY2D-A27OC8C52F6M");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject job=new JSONObject();
try {
job.accumulate("aloha", jo);
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Log.e("url", job.toString());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.url);
try {
httppost.setEntity(new StringEntity(job.toString(), "UTF- 8"));
// httppost.toString();
// Log.e("url", httppost.toString());
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity httpentity = httpresponse.getEntity();
is = httpentity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while((line = reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
json = sb.toString();
Log.e("url", json);
try {
jobj = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jobj;
}

Unable to insert row from Android to MySQL using PHP

I am trying to insert data from android to MySQL but it does not show any error in logcat but displays the json message in the app.
Here is my PHP script.
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
require("config.inc.php");
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['userName']) && isset($_POST['userContact']) && isset($_POST['userAddress']) && isset($_POST['userStore']) && isset($_POST['userRequest'])) {
$userName = $_POST['userName'];
$userContact = $_POST['userContact'];
$userAddress = $_POST['userAddress'];
$userStore = $_POST['userStore'];
$userRequest = $_POST['userRequest'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO userrequests(userName, contactNumber, userAddress, storeList, requestBody) VALUES('$userName', '$userContact', '$userAddress', '$userStore', '$userRequest')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "IsitdispllayingthusOops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Here is my JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.i("log_tag","Line reads: " + line);
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Here is my MainActivity.java
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private EditText userName, userContact, userAddress, userRequest;
private Spinner userStore;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://10.0.2.2/callarocket/register.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner dropdown = (Spinner)findViewById(R.id.StoreSpinner);
String[] items = new String[]{"NZ Mamak", "Indo Shop", "NZ Supermarket"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
userName = (EditText)findViewById(R.id.EditName);
userContact = (EditText)findViewById(R.id.EditContact);
userAddress = (EditText)findViewById(R.id.EditAddress);
userStore = (Spinner)findViewById(R.id.StoreSpinner);
userRequest = (EditText)findViewById(R.id.EditRequest);
mRegister = (Button)findViewById(R.id.SubmitButton);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating Request...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = userName.getText().toString();
String usercontact = userContact.getText().toString();
String useraddress = userAddress.getText().toString();
String userstore = userStore.getSelectedItem().toString();
String userrequest = userRequest.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", username));
params.add(new BasicNameValuePair("userContact", usercontact));
params.add(new BasicNameValuePair("userAddress", useraddress));
params.add(new BasicNameValuePair("userStore", userstore));
params.add(new BasicNameValuePair("userRequest", userrequest));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
And the error I am getting inside the emulator is this json message in my php script
$response["message"] = "IsitdispllayingthusOops! An error occurred.";
I couldn't find the reason why new row cannot be inserted into MySQL.
POST can not be used by external applications. You have to use GET instead.

Login 404 Parse.com REST API Java

We decided to build our own twitter login for aesthetic reasons rather than use ParseTwitterUtils.login(), and we are having to login through the REST API (unless someone has a better idea on how to get a session token for a user with twitterAuth).
So currently it is set up as such:
private class ParseLogin extends AsyncTask<String, String, Boolean> {
JSONObject authData;
JSONObject wrapper;
#Override
protected void onPreExecute() {
try {
authData = new JSONObject();
wrapper = new JSONObject();
JSONObject twitterAuth = new JSONObject();
twitterAuth.put("id", Long.toString(twitterUser.getId()));
twitterAuth.put("screen_name", twitterUser.getScreenName());
twitterAuth.put("consumer_key", CONSUMER_KEY);
twitterAuth.put("consumer_secret", CONSUMER_SECRET);
twitterAuth.put("auth_token", accessToken.getToken());
twitterAuth.put("auth_secret", accessToken.getTokenSecret());
authData.put("twitter", twitterAuth);
wrapper.put("authData", authData);
} catch (JSONException e)
{
e.printStackTrace();
}
}
#Override
protected Boolean doInBackground(String... args) {
// Send the HttpPostRequest and receive a JSONObject in return
JSONObject jsonObjRecv = JSONRequest.SendHttpGet("https://api.parse.com/1/users/", wrapper);
return true;
}
#Override
protected void onPostExecute(Boolean response) {
}
}
Which then in turns sends the login request to the REST API via here
public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGetWithEntity httpPostRequest = new HttpGetWithEntity(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("X-Parse-Application-Id", APP KEY);
httpPostRequest.setHeader("X-Parse-REST-API-Key", REST API KEY);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
Log.d("JSON RESULT", resultString);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
// Transform the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
Any ideas on the 404?
Edit: Fixed - Use /Users/ instead of /Login/ for 3rd party auth, changes from GET to POST
private class ParseLogin extends AsyncTask<String, String, Boolean> {
JSONObject authData;
JSONObject wrapper;
#Override
protected void onPreExecute() {
try {
authData = new JSONObject();
wrapper = new JSONObject();
JSONObject twitterAuth = new JSONObject();
twitterAuth.put("id", Long.toString(twitterUser.getId()));
twitterAuth.put("screen_name", twitterUser.getScreenName());
twitterAuth.put("consumer_key", CONSUMER_KEY);
twitterAuth.put("consumer_secret", CONSUMER_SECRET);
twitterAuth.put("auth_token", accessToken.getToken());
twitterAuth.put("auth_token_secret", accessToken.getTokenSecret());
authData.put("twitter", twitterAuth);
wrapper.put("authData", authData);
} catch (JSONException e)
{
e.printStackTrace();
}
}
#Override
protected Boolean doInBackground(String... args) {
// Send the HttpPostRequest and receive a JSONObject in return
JSONObject jsonObjRecv = JSONRequest.SendHttpGet("https://api.parse.com/1/users/", wrapper);
return true;
}
#Override
protected void onPostExecute(Boolean response) {
}
And then the Get (which is actually a post, just need to changed the method name)
public static JSONObject SendHttpGet(String URL, JSONObject jsonObjSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("X-Parse-Application-Id", APP ID);
httpPostRequest.setHeader("X-Parse-REST-API-Key", REST API KEY);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
//httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
Log.d("JSON RESULT", resultString);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
// Transform the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
}
}
catch (Exception e)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
e.printStackTrace();
}
return null;
}
Fixed it. Should have been a POST to /Users/ rather than a GET from /Login/. Sharing incase anyone else runs into this.
private class ParseLogin extends AsyncTask {
JSONObject authData;
JSONObject wrapper;
#Override
protected void onPreExecute() {
try {
authData = new JSONObject();
wrapper = new JSONObject();
JSONObject twitterAuth = new JSONObject();
twitterAuth.put("id", Long.toString(twitterUser.getId()));
twitterAuth.put("screen_name", twitterUser.getScreenName());
twitterAuth.put("consumer_key", CONSUMER_KEY);
twitterAuth.put("consumer_secret", CONSUMER_SECRET);
twitterAuth.put("auth_token", accessToken.getToken());
twitterAuth.put("auth_token_secret", accessToken.getTokenSecret());
authData.put("twitter", twitterAuth);
wrapper.put("authData", authData);
} catch (JSONException e)
{
e.printStackTrace();
}
}
#Override
protected Boolean doInBackground(String... args) {
// Send the HttpPostRequest and receive a JSONObject in return
JSONObject jsonObjRecv = JSONRequest.SendHttpGet("https://api.parse.com/1/users/", wrapper);
return true;
}
#Override
protected void onPostExecute(Boolean response) {
}
And then the Get (which is actually a post, just need to changed the method name)
public static JSONObject SendHttpGet(String URL, JSONObject jsonObjSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("X-Parse-Application-Id", APP ID);
httpPostRequest.setHeader("X-Parse-REST-API-Key", REST API KEY);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
//httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
Log.d("JSON RESULT", resultString);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
// Transform the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
}
}
catch (Exception e)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
e.printStackTrace();
}
return null;
}

Android : JSON Parser with async task (GET and POST methods)

Just want to check whether this JSON Parser with async task is it correctly done? When I put this code into my Eclipse, this (method.equals("POST") was underline red. And it state that the 'method' cannot be solved. Any suggestion or help in this? Thank you.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String url=null;
List<NameValuePair> nvp=null;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
BackGroundTask Task= new BackGroundTask(url, method, params);
try {
return Task.execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
List<NameValuePair> postparams= new ArrayList<NameValuePair>();
String URL=null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
URL=url;
postparams=params;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
}
You forgot to declare method property in your BackGroundTask class.
EDIT Like this:
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
List<NameValuePair> postparams= new ArrayList<NameValuePair>();
String URL=null;
String method = null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
URL=url;
postparams=params;
this.method = method;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
}
You need to set method as a class variable within BackGroundTask. You are passing it into the constructor but not going anything with it. Set it the same way you have done with url and postparams.

Categories

Resources