my HttpGet request is calling my indexAction, instead of getAction. What's going on?
Here are my codes:
public function getAction() {
$id = $this->_getParam('id');
if(!$id)
{
$this->getResponse()
->setHttpResponseCode(400)
->setBody("no id");
return;
}
try
{
$q = Doctrine_Query::create()
->from('Milotin_Model_Locations l')
->where ('l.id=?', $id);
$result = $q->fetchArray();
if(count($result) == 1)
{
$this->getResponse()
->setHttpResponseCode(200)
->setBody(json_encode($result));
}
}
catch(Exception $e)
{
$this->getResponse()
->setHttpResponseCode(500)
->setBody($e->getMessage());
}
}
public function indexAction() {
}
And here is my code in Android:
private static void getLoc()
{
final HttpResponse response;
final HttpGet getRequest = new HttpGet(LOCATION_URI + "?geolat=" + geoLat + "&geolong=" + geoLong);
try {
response = mHttpClient.execute(getRequest);
if(response.getStatusLine().getStatusCode() == 200)
{
//do something
}
} catch (ClientProtocolException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
}
My HttpPost is working correctly (it calls postAction), Any explanation?
Thanks.
I found the answer. It's actually the behavior of Zend Framework. If the 'id' element is not found in the GET request, it will redirect to indexAction, instead of getAction.
Example:
'GET localhost/student' will redirected to indexAction, while
'GET localhost/student/23' will redirected to getAction. (23 is the id)
Found it in Zend Framework: A beginner's guide, by Vikram Vaswani.
Related
Hey guys i have implemented twitter sharing in my app and got some problem it gave 215 in response
TwitterCore.getInstance().logInGuest(new Callback<AppSession>() {
#Override
public void success(Result<AppSession> result) {
guestAppSession = result.data;
try {
Log.d("guestAppSession" + guestAppSession.getAuthToken(),
"=" + result.data.getId());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Log.d("URL", "=" + url);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI(url));
HttpResponse res = client.execute(method);
inputStream = res.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
Log.d("bufferedReader_", "=" + bufferedReader.readLine());
while(bufferedReader.readLine() != null)
{
Log.d("bufferedReader", "=" + bufferedReader.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void failure(TwitterException exception) {
// unable to get an AppSession with guest auth
}
});
above is my code let me know what is wrong. and give me proper response to implement it...
Thanks ..
Error code: {"errors":[{"code":215,"message":"Bad Authentication data."}]}
I have solved my problem as ..
TwitterCore.getInstance().logInGuest(
new Callback<AppSession>() {
#Override
public void success(
Result<AppSession> appSessionResult) {
AppSession guestAppSession = appSessionResult.data;
final TwitterApiList apiClient = new TwitterApiList(
guestAppSession);
apiClient.getListService().statuses(
" shjh", "user",
50, new Callback<List<Tweet>>() {
#Override
public void success(
Result<List<Tweet>> listResult) {
Log.d("twittercommunity",
"user's profile url is "
+ listResult.data
.get(0).user.profileBackgroundColor);
// Do something with the
// list
}
}
#Override
public void failure(
TwitterException e) {
// FAIL
}
});
}
#Override
public void failure(TwitterException e) {
e.printStackTrace();
}
});
When I run the following code, I get a "connection reset by peer" exception in most instances.
String rest = System.setProperty("http.keepAlive", "false");
String uri = WEB_LOG_IN + "?user_username=" + user_email
+ "&user_password=" + user_pass + "&user_mac=" + user_mac;
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uri);
HttpResponse response;
String s;
try {
response = client.execute(httppost);
s = new String(EntityUtils.toByteArray(response.getEntity()),
"UTF-8");
// read json
if (s.length() > 2)
return readlogin_info(s);
else
return false;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
String rest = System.setProperty("http.keepAlive", "false");
returns null which means no "http.keepAlive" property.
I tried using httpurlconnection, but that also didn't work.
I am so confused because I think the code works without issue for some ISPs.
Based on my investigation the exception caused by Mikrotik Router latency! (Maybe! Please correct me if I am wrong!)
so I put the execute section in a while until it can get the answer from server, after multiple execution I see after 2 times of trying to connect it successfully get the answer.
int count = 0;
while (s == null) {
count++;
try {
response = client.execute(httpGet);
s = new String(
EntityUtils.toByteArray(response.getEntity()),
"UTF-8");
// read json
if (s.length() > 2)
{
return readlogin_info(s);
}
else
{
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
I'm using the following code to post to a Google Form. If the HTTP response is not successful then the record is not marked as sent from the sqlite database and is resent during the next sync operation. The problem is I see frequent double posts because a response is not received even though the post was successful.
Is there a better way to confirm the post without creating double posts to the form?
Thanks for your help.
private Boolean performPost(String...data){
prefs = UserData.getPrefs(mContext);
spreadsheetKey = prefs.getString(UserData.PREF_SPREADSHEET_KEY,"");
ArrayList<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=" + spreadsheetKey);
int counter = 0;
for (String s : data){
results.add(new BasicNameValuePair("entry." + counter + ".single", s));
counter ++;
}
try {
post.setEntity(new UrlEncodedFormEntity(results));
} catch (UnsupportedEncodingException e) {
// Auto-generated catch block
Log.e(TAG, "An error has occurred", e);
}
try {
//client.execute(post);
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
returnCode = statusLine.getStatusCode();
Log.d(TAG, statusLine+ "\n"+ returnCode + " " + String.valueOf(post.getEntity()));
response.getEntity().consumeContent();
} catch (ClientProtocolException e) {
// Auto-generated catch block
Log.e(TAG, "client protocol exception", e);
} catch (IOException e) {
// Auto-generated catch block
Log.e(TAG, "io exception", e);
}
if (returnCode == 200){
return true;
}else{
resultTxt = SYNC_UNSUCCESSFUL_HTTP_ERROR;
Log.e(TAG,"post unsuccessful, http code :" + String.valueOf(returnCode));
sendBroadcast();
return false;
}
}
I'm trying to connect to Google tasks without using Google client libraries. The following code returns a 403 forbidden error. Just not sure what I'm missing. Any guidance would be appreciated.
try {
Bundle options = new Bundle();
AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccountsByType("com.google");
Account acct = list[0];
manager.invalidateAuthToken("com.google", null);
AccountManagerFuture<Bundle> acc = manager.getAuthToken(
acct,
"oauth2:https://www.googleapis.com/auth/tasks",
options, true, null, null);
Bundle bundle = acc.getResult();
String token = bundle
.getString(AccountManager.KEY_AUTHTOKEN);
Log.i("Token: ", token); // token does have value
String url = "https://www.googleapis.com/tasks/v1/users/#me/lists?key=long_winded_api_key_from_console_here";
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("client_id",
"clientID_from_console_here.apps.googleusercontent.com");
getRequest.addHeader("Authorization", "OAuth " + token);
HttpClient httpclient = new DefaultHttpClient();
String responseBody = httpclient.execute(getRequest,
new BasicResponseHandler()); // exception raised here
httpclient.execute(getRequest, new BasicResponseHandler());
Log.i("###", responseBody); // cannot get the response here
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // exception raised here
catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
The following link shows how to get started using the Google Drive API from Android. It lets the user pick an account, gets consent from them then acquires a credentials object that can be used for API access with the Google client libraries:
https://developers.google.com/drive/quickstart-android
In your case you are trying to use the Tasks API, however the authentication parts should be identical:
In Step 2, enable the Tasks API instead.
Step 4 shows how to get an access token for a particular scope:
credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
Change the scope to the task API scope: https://www.googleapis.com/auth/tasks
Then I would recommend using the Google client libraries for the rest like the Drive example.
If for any reason you don't want to use the client libraries, and prefer crafting the HTTP request yourself, the authorization header you want should look like the following (unable to test right now):
getRequest.addHeader("Authorization", "Bearer " + credential.getToken());
I'm not perfectly sure if this is the cause, since you seem to do the same steps
I do, but you might want to try to use "Manage your tasks" instead of
"oauth2:https://www.googleapis.com/auth/tasks". That might be the reason for
the 403.
Here is how I connect without client libraries.
Full source available here:
apiTalker
First I get the access token:
public static final String AUTH_TOKEN_TYPE = "Manage your tasks";
public static String getAuthToken(AccountManager accountManager,
Account account, String authTokenType, boolean notifyAuthFailure) {
Log.d(TAG, "getAuthToken");
String authToken = "";
try {
// Might be invalid in the cache
authToken = accountManager.blockingGetAuthToken(account,
authTokenType, notifyAuthFailure);
accountManager.invalidateAuthToken("com.google", authToken);
authToken = accountManager.blockingGetAuthToken(account,
authTokenType, notifyAuthFailure);
}
catch (OperationCanceledException e) {
}
catch (AuthenticatorException e) {
}
catch (IOException e) {
}
return authToken;
}
Connecting and listing the available tasklists:
public static final String BASE_URL = "https://www.googleapis.com/tasks/v1/users/#me/lists";
public static String AuthUrlEnd() {
return "key=" + Config.GTASKS_API_KEY;
}
public static String AllLists(final String pageToken) {
String result = BASE_URL + "?";
if (pageToken != null && !pageToken.isEmpty()) {
result += "pageToken=" + pageToken + "&";
}
result += AuthUrlEnd();
return result;
}
public String getListOfLists(ArrayList<GoogleTaskList> list)
throws ClientProtocolException, IOException, JSONException {
String eTag = "";
String pageToken = null;
do {
HttpGet httpget = new HttpGet(AllLists(pageToken));
httpget.setHeader("Authorization", "OAuth " + authToken);
// Log.d(TAG, "request: " + AllLists());
AndroidHttpClient.modifyRequestToAcceptGzipResponse(httpget);
try {
JSONObject jsonResponse = (JSONObject) new JSONTokener(
parseResponse(client.execute(httpget))).nextValue();
// Log.d(TAG, jsonResponse.toString());
if (jsonResponse.isNull(NEXTPAGETOKEN)) {
pageToken = null;
}
else {
pageToken = jsonResponse.getString(NEXTPAGETOKEN);
}
// No lists
if (jsonResponse.isNull("items")) {
break;
}
eTag += jsonResponse.getString("etag");
JSONArray lists = jsonResponse.getJSONArray("items");
int size = lists.length();
int i;
// Lists will not carry etags, must fetch them individually if
// that
// is desired
for (i = 0; i < size; i++) {
JSONObject jsonList = lists.getJSONObject(i);
//Log.d("nononsenseapps", jsonList.toString(2));
list.add(new GoogleTaskList(jsonList, accountName));
}
}
catch (PreconditionException e) {
// // Can not happen in this case since we don't have any etag!
// } catch (NotModifiedException e) {
// // Can not happen in this case since we don't have any etag!
// }
}
} while (pageToken != null);
return eTag;
}
Here is how I parse the response:
public static String parseResponse(HttpResponse response)
throws ClientProtocolException, PreconditionException {
String page = "";
BufferedReader in = null;
Log.d(TAG, "HTTP Response Code: "
+ response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 403) {
// Invalid authtoken
throw new ClientProtocolException("Status: 403, Invalid authcode");
}
else if (response.getStatusLine().getStatusCode() == 412) { //
/*
* Precondition failed. Object has been modified on server, can't do
* update
*/
throw new PreconditionException(
"Etags don't match, can not perform update. Resolve the conflict then update without etag");
}
/*
* else if (response.getStatusLine().getStatusCode() == 304) { throw new
* NotModifiedException(); }
*/
else if (response.getStatusLine().getStatusCode() == 400) {
// Warning: can happen for a legitimate case
// This happens if you try to delete the default list.
// Resolv it by considering the delete successful. List will still
// exist on server, but all tasks will be deleted from it.
// A successful delete returns an empty response.
// Make a log entry about it anyway though
Log.d(TAG,
"Response was 400. Either we deleted the default list in app or did something really bad");
throw new PreconditionException(
"Tried to delete default list, undelete it");
}
else if (response.getStatusLine().getStatusCode() == 204) {
// Successful delete of a tasklist. return empty string as that is
// expected from delete
Log.d(TAG, "Response was 204: Successful delete");
return "";
}
else {
try {
if (response.getEntity() != null) {
// Only call getContent ONCE
InputStream content = AndroidHttpClient
.getUngzippedContent(response.getEntity());
if (content != null) {
in = new BufferedReader(new InputStreamReader(content));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
page = sb.toString();
//
// System.out.println(page);
}
}
}
catch (IOException e) {
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
return page;
}
I am working with Android http stuff to register/unregister to the server. I have a DELETE request to use HttpDelete. I am getting Http401 'Bad request' error when I try to call it. I cannot why it is happening. Please help me.
Here is my code:
HttpUtils.java
private BasicHttpParams mParams;
private UsernamePasswordCredentials mCredentials = null;
private ResponseHandler mResponseHandler = null;
public void setUserCredentials(String userName, String password) {
this.mCredentials = new UsernamePasswordCredentials(userName, password);
}
public void setResponseHandler(ResponseHandler responseHandler){
this.mResponseHandler = responseHandler;
}
public Result<String> delete(String url){
Result<String> result = new Result<T>();
result.setStatus(Result.FAIL);
try {
DefaultHttpClient httpClient = new DefaultHttpClient(mParams);
httpClient.setParams(mParams);
httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), mCredentials);
HttpResponse response = httpClient.execute(new HttpDelete(url));
result.setResult(mResponseHandler.handleResponse(response));
result.setStatus(Result.SUCCESS);
} catch (IllegalArgumentException e) {
e.printStackTrace();
result.setMessage(e.getMessage());
} catch (ClientProtocolException e) {
e.printStackTrace();
result.setMessage(e.getMessage());
} catch (ConnectTimeoutException e) {
result.setMessage("Connection timed out.");
} catch (IOException e) {
e.printStackTrace();
result.setMessage(e.getMessage());
}
return result;
}
UnregisterTask.java
#Override
protected Void doInBackground(String... urls) {
if (urls==null || urls.length!=1)
return null;
String url = urls[0];
HttpUtils httpUtils = new HttpUtils();
httpUtils.setUserCredentials("userid", "password");
httpUtils.setResponseHandler(new UnrgisterHandler());
httpUtils.delete(url);
Result<String> result = aClient.delete(url);
if (result!=null || result.result != null){
//Do Something
}
}
//UnrgisterActivity.java
public void onUnregisterButtonClick(View view){
UnregisterTask task = new UnregisterTask(this);
task.execute(ServerConfig.getIdmServer() + ServerConfig.DELETE_DEVICE + "myid");
}
Error recevied:
Apache Tomcat/7.0.26 - Error report HTTP Status 400 - type Status reportmessage description The request sent by the client was syntactically incorrect ().Apache Tomcat/7.0.26
Thanks in Advance.
I fixed it by myself but I do not understand clearly why the error happened. I changed my code after searching how to set basic authentication.
public Result<T> delete(String url)
Result<T> result = new Result<T>();
result.setStatus(Status.FAIL);
try {
DefaultHttpClient http = new DefaultHttpClient();
if (this.mCredentials!=null){
CredentialsProvider credProvider = new BasicCredentialsProvider();
credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), this.mCredentials);
http.setCredentialsProvider(credProvider);
}
HttpDelete delete = new HttpDelete(url);
//delete.setEntity(new StringEntity(data, "UTF8"));
delete.addHeader("Content-type", JSON_TYPE);
HttpResponse response = http.execute(delete);
result.setResult(mResponseHandler.handleResponse(response));
result.setStatus(Result.Status.SUCCESS);
} catch (IllegalArgumentException e) {
e.printStackTrace();
result.setMessage(e.getMessage());
} catch (ClientProtocolException e) {
e.printStackTrace();
result.setMessage(e.getMessage());
} catch (ConnectTimeoutException e) {
result.setMessage("Connection timed out.");
} catch (IOException e) {
e.printStackTrace();
result.setMessage(e.getMessage());
}
return result;
}
A bit still confusing. Anyway, now it works charm.