Call mail PHP file from Android doesn't work - java

I have the following function in my Android app:
void sendEmail(String PHPfileUurl, String receiverEmail, String fromEmail) {
ParseUser currentUser = ParseUser.getCurrentUser();
StringBuilder messageBuilder = new StringBuilder();
for (int i=0; i<productsOrdered.size(); i++){
messageBuilder.append(productsOrdered.get(i)).append("\n");
}
String mess = messageBuilder.toString();
String parameters = "name=" + currentUser.getString(Configurations.USER_FULLNAME) +
"&fromEmail=" + fromEmail +
"&receiverEmail=" + receiverEmail +
"&messageBody=" + mess +
"&storeName=" + Configurations.MERCHANT_NAME +
"&shippingAddress=" + currentUser.getString(Configurations.USER_SHIPPING_ADDRESS);
String strURL = PHPfileUurl + parameters;
strURL = strURL.replace(" ", "%20");
strURL = strURL.replace("\n", "%20");
Log.i(Configurations.TAG, "PHP STRING URL: " + strURL);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url;
url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(20000);
conn.setReadTimeout(20000);
conn.setDoInput(true);
conn.setDoOutput(true);
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
InputStream is = conn.getInputStream();
Log.i(Configurations.TAG, "EMAIL RESPONSE: " + conn.getResponseMessage());
} else {
InputStream err = conn.getErrorStream();
Log.i(Configurations.TAG, "ERROR ON EMAIL: " + err);
}
} catch (IOException e) {e.printStackTrace(); }
}
When I call that function the Logcat prints out this message:
I/log-: PHP STRING URL: http://example.com/myapp/email-admin.php?name=Mark%20Doe&fromEmail=myemail#gmail.com&receiverEmail=admin#mydomain.com&messageBody=PRODUCT%20ID:%20Q3nQgZdlFG%20---%20PRODUCT:%20Nike%20Sport%20Shoes%20black%20%20---%20QUANTITY:%201%20---%20SIZE:%20L%20&storeName=Z%20Store%20Inc.&shippingAddress=John%20Doe,%20121%20Church%20Avenue,%20ASD123,%20London,%20UK
I/log-: EMAIL RESPONSE: OK
So I assume everything is fine since the RESPONSE = OK. But it's not, because I will not receive any email at admin#mydomain.com (there is another email address, I've posted a fake one just as an example, the Logcat prints out my real email address as receiverEmail).
Here's my mail.php file:
// POST Variables
$name = $_POST['name'];
$fromEmail = $_POST['fromEmail'];
$receiverEmail = $_POST['receiverEmail'];
$messageBody = $_POST['messageBody'];
$storeName = $_POST['storeName'];
$shippingAddress = $_POST['shippingAddress'];
$headers = 'From: ' .$fromEmail;
// SUBJECT
$subject = "New order from " .$name. " on '" .$storeName. "'";
// COMPOSE MESSAGE
$message =
"ORDER DETAILS:\n".
$messageBody.
"\n\nName: " .$name.
"\nUser Email: " .$fromEmail.
"\nShipping Address: " .$shippingAddress
;
/* Finally send email */
mail($receiverEmail,
$subject,
$message,
$headers
);
/* Result */
echo "Email Sent to: " .$receiverEmail. "\n Message: " .$message;
Does my code have something wrong? is there another way to call a mail.php file from my own server? I've also tried this question, but I cannot import the DefaultHttpClient class in my project.

it's would be easier if you change the $_POST to $_GET
but the problem in the $_GET method if the message have (&something=) inside
it you will receive only half the message as the &something= would be set to an other $_GET , Also you might get some problems if the message is too long ,
so if you want to use the $_POST method instead of the $_GET
you need to change your java code ,
make sure to import Map and then change it to this
void sendEmail(String PHPfileUurl, String receiverEmail, String fromEmail) {
ParseUser currentUser = ParseUser.getCurrentUser();
StringBuilder messageBuilder = new StringBuilder();
for (int i=0; i<productsOrdered.size(); i++){
messageBuilder.append(productsOrdered.get(i)).append("\n");
}
String mess = messageBuilder.toString();
Map<String,Object> params = new LinkedHashMap<>();
params.put("name", currentUser.getString(Configurations.USER_FULLNAME));
params.put("fromEmail", fromEmail);
params.put("receiverEmail", receiverEmail);
params.put("messageBody", mess);
params.put("storeName", Configurations.MERCHANT_NAME);
params.put("shippingAddress", currentUser.getString(Configurations.USER_SHIPPING_ADDRESS);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
String strURL = PHPfileUurl;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url;
url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(20000);
conn.setReadTimeout(20000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
InputStream is = conn.getInputStream();
Log.i(Configurations.TAG, "EMAIL RESPONSE: " + conn.getResponseMessage());
} else {
InputStream err = conn.getErrorStream();
Log.i(Configurations.TAG, "ERROR ON EMAIL: " + err);
}
} catch (IOException e) {e.printStackTrace(); }
}

Use $_GET instead of $_POST ,
change all variable from
$name = $_POST['name'];
to
$name = $_GET['name'];

Related

HttpsURLConnection 400 Bad Request error occured

I need to convert below Swift code to Java.
Swift code works.
But, Java code is not worked.
HttpsURLConnection has failed.
responseCode: 400 (HttpsURLConnection.getResponseCode())
message2: Bad Request (HttpsURLConnection.getResponseMessage())
How can I solve 400 Bad Request error.
In Swift(It worked)
func sendNotification(token: String, message: String) {
//Firebase CloudMessaging serverkey
var firebaseServerKey = "AAAAA6qLps4:APA91bE7szGAgp3qYGOJsrSsrM1InhIgf5Fq1xxxxxx"
let url = URL(string: "https://fcm.googleapis.com/fcm/send")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("key=\(firebaseServerKey)", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
request.httpBody = "{\"to\":\"\(token)\",\"notification\":{\"body\":\"\(message)\",\"badge\":\"1\"}}".data(using: .utf8)
}
I wrote in JAVA(not worked)
private void sendNotification(String token, String message) {
//Firebase CloudMessaging serverkey
var firebaseServerKey = "AAAAA6qLps4:APA91bE7szGAgp3qYGOJsrSsrM1InhIgf5Fq1xxxxxx"
try {
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+firebaseServerKey);
String str = "{\"to\": " + token + ", \"notification\": { \"body\": " + message + ", \"badge\": \"1\"}}";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.close();
int responseCode = conn.getResponseCode(); // responseCode: 400
if (responseCode == HttpsURLConnection.HTTP_OK) {
Log.d("Success", String.valueOf(responseCode));
} else {
String code = String.valueOf(responseCode);
String message2 = conn.getResponseMessage(); // message2: Bad Request
Log.d("Fail", String.valueOf(responseCode));
Log.d("Fail2", conn.getResponseMessage());
}
}
Your JSON request body is incorrect. It produce {"to": zxc} which is an invalid json. Change it to
String str = "{\"to\": \"" + token + "\", \"notification\": { \"body\": \"" +
message + "\", \"badge\": \"1\"}}";

I'd like to send list to php file and save list to mysqli

Hi i'm trying to send course list which has more than 2,000 course info to mysqli through php file. but ! whenever i try to send list, it doesn't send it to server.
so can you help me to solve this problem..? :(
First, java source
public static void sendCourseInfoToDB(List<Subject> subjects, String url) {
try {
// url is my *.php file
URL target = new URL(url);
HttpURLConnection con = (HttpURLConnection) target.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "text/html; charset = utf-8");
DataOutputStream out = new DataOutputStream(con.getOutputStream());
int len = subjects.size();
for (int i = 0; i < len; ++i) {
//String t = subjects.get(i).toString();
out.writeBytes(subjects.get(i).toString());
out.flush();
}
out.flush();
out.close();
int responseCode = con.getResponseCode();
System.out.println("Post rqeust to Url : " + url);
System.out.println("Post Params : " + subjects.get(0).toString());
System.out.println("Resoponse Code : " + Integer.toString(responseCode));
con.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
Subject class overrides toString. return-statement used parameter is encoded UTF-8
like this :
courseCode = 12156&courseName = %EC%8B%A0%EC%86%8C%EC%9E%AC%EA%B3%B5%ED%95%99%EB%B6%80&subjectName = %EC%A2%85%ED%95%A9%EA%B3%BC%EC%A0%9C%EC%84%A4%EA%B3%841&kindOfSubject = %EC%A0%84%EA%B3%B5&score = 2
and php file
<?php
header("Content-Type : text/html; charset = utf-8");
$mysqli = new mysqli("localhost", "user", "password", "db");
if($mysqli->mysqli_errno) {
print $mysqli_error;
exit();
}
$courseCode = $_POST["courseCode"];
$courseName = $_POST["courseName"];
$subjectName = $_POST["subjectName"];
$kindOfSubject = $_POST["kindOfSubject"];
$score = $_POST["score"];
$mysqli->query("INSERT INTO COURSE VALUES('$courseCode', '$courseName', '$subjectName', '$kindOfSubject', '$score')");
$response = $courseCode;
echo $response;
?>
should i call 'sendCourseInfoToDB function every time when i send course info to DB ? i dont know what is wrong.. help me crazy coding people~!~

JSONException: A JSONObject text must begin with '{' at character 1 error in HTTPS POST response

I am trying to POST HTTPS request to one of the client's server. In turn the response which is returned back from the server is missing "{" from the JSON response.
When the client is testing they are receiving proper response.
Can you please help me out on debugging whats an issue with the code content. The same issue persist of missing "<" character in
XML response while changing the header to "Accept", "application/xml".
// Request headers that needs to be passed
public Object generateHttpHeader(String requestType, IYodRobot pRobot, Object request) {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Connection"," Keep-Alive");
headers.put("Content-type", "application/x-www-form-urlencoded");
headers.put("Accept", "application/json");
headers.put("Accept-Language", "en-US");
headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)");
headers.put("Accept-Encoding", "identity");
headers.put("Cookie", "Aggregator=stuff");
// Headers generated that need to be passed.
return headers;
}
// Posting request
protected String postRequestLocal(Object generateHttpHeader){
URL url;
HttpsURLConnection urlConn;
//Generating HTTPS connection object
OutputStreamWriter wout = null;
BufferedReader br = null;
StringBuffer ResponseData = new StringBuffer();
InputStreamReader isr = null;
String contents = "";
String reasonForRetry = "";
String URL = "https://XXXXXXX/service/Servlet";
//Constructing request
String request = "UID=" + "abcdefgh" + "&KEY=" + "12344";
System.out.println("2^^^^^^^ URL is: " + URL);
System.out.println("Request is ::"+request);
try {
//URL connection creation
url = new URL(URL);
urlConn = (javax.net.ssl.HttpsURLConnection)
url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setInstanceFollowRedirects(false);
String clientKeyStore = "XXXXXXXX";
String password = "XXXXXX";
// 2- WAY SSL Connectivity
urlConn.setSSLSocketFactory(getFactory(new File("/XXX/XXX/XX/XXX/" + clientKeyStore), password));
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.connect();
HashMap<String, String> headers = (HashMap<String, String>) generateHttpHeader;
System.out.println("2^^^^^^^^^^^^^printing url connection " + urlConn.toString());
for (Iterator<Map.Entry<String, String>> headerIter = headers.entrySet().iterator();
headerIter.hasNext();) {
System.out.println(" In here.......................");
Map.Entry<String, String> entry = headerIter.next();
urlConn.setRequestProperty(entry.getKey(), entry.getValue());
System.out.println("2^^^^^^^ printing key " + entry.getKey().toString() + " value is" +
entry.getValue().toString());
}
//Hashmap for request headers that needs to be passed`enter code here`
Map<String, List<String>> requestHeaders = urlConn.getRequestProperties();
YDataLogger.out("2^^^^^^^^^^Request Header Fields is: "+ requestHeaders);
YDataLogger.out("urlConn.getRequestMethod"+urlConn.getRequestMethod());
wout = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
System.out.println("2^^^^^^^^^checkpoint 8");
wout.write(request);
System.out.println("2^^^^^^^^^wout" + wout.toString());
wout.flush();
wout.close();
/*
* Getting the soap error message if we have error.
*/
System.out.println("2^^^ Trying to print the fault");
System.out.println("2^^^^^^ urlConngetResponseCode--->" + urlConn.getResponseCode());
System.out.println("2^^^^^^ urlConngetResponseMessage--->" + urlConn.getResponseMessage());
if (urlConn.getResponseCode() == 200) {
isr = new InputStreamReader(urlConn.getInputStream());
} else if(urlConn.getResponseCode() == 500) {
throw new SiteApplicationErrorException("Server down", urlConn.getResponseMessage());
}
else {
isr = new InputStreamReader(urlConn.getErrorStream());
}
Map<String, List<String>> responseHeaders = urlConn.getHeaderFields();
System.out.println("2^^^^^^^^^^Response Header Fields is: "+responseHeaders);
System.out.println("2^^^^^^^ response header---"+urlConn.getHeaderFields());
br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
ResponseData.append(s);
}
//Diconnecting URL connecttion
urlConn.disconnect();
/*
* getting the soap Data/Message if we have error.
*/
Date end = new Date();
System.out.println("2^^^ Properties" + urlConn.getRequestProperties());
System.out.println("2^^^^^" + end.toLocaleString());
contents = ResponseData.toString();
}
//catching exception
catch (Exception ex) {
System.out.println("2^^^^^ getStackTrace-->\n" + getStackTrace(ex));
reasonForRetry = ex.getMessage();
Printing stack trace in case of https failure
if (ex.getMessage().contains(
"server returned http response code: 500")) {
throw new SiteApplicationErrorException(
"2^^^^Top Level Error - Returned HTTP response code: 500 :: Exact error"
+ ex.getMessage());
} else {
System.out.println("2^^^^^ getStackTrace-->\n" + getStackTrace(ex));
throw new GeneralException(ex.toString() + "\n"
+ ex.getMessage());
}
} finally {
if (wout != null) {
wout.close();
}
if (isr != null) {
isr.close();
}
}
// Printing the response returned back
System.out.println("2^^^^^^^^^Contents : "+contents);
}
My guess is that the webservice expects the parameters UID and KEY to be passed as JSON (or XML), not application/x-www-form-urlencoded.

Unable to set Authorization header of HttpsURLConnection

I'm trying to set the OAuth Authorization header of a HttpsURLConnection object and below is the java code for that
String url1 = "/data/ServiceAccount?schema=1.0&form=json&byBillingAccountId={EQUALS,xyz#pqr.edu}";
String url = "https://secure.api.abc.net/data/ServiceAccount?schema=1.0&byBillingAccountId={EQUALS,xyz#pqr.edu}";
String header = OAuthClient.prepareURLWithOAuthSignature(url1);
HttpsURLConnection con = null;
try {
URL obj = new URL(url);
con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", "OAuth " + header);
System.out.println("Request properties = " + con.getRequestProperty("Authorization"));
int responseCode = con.getResponseCode();
System.out.println("Response Code = " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
con.disconnect();
//print result
System.out.println("Response = " + response.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(con!=null) con.disconnect();
}
And below is the code for prepareURLWithOAuthSignature
public String prepareURLWithOAuthSignature(String url)
{
String signature = null;
setOAuthParameters();
setOAuthQParams();
try
{
httpURL = URLEncoder.encode(baseURL+url, "UTF-8");
signature = OAuthSignatureService.getSignature(httpURL, URLEncoder.encode(URLEncodedUtils.format(qparams, "UTF-8"), "UTF-8"), consumer_secret);
OAuthParameters.put("oauth_signature", signature);
} catch (Exception e) {
e.printStackTrace();
}
return getOAuthAuthorizationHeader();
}
public String getOAuthAuthorizationHeader()
{
String OAuthHeader = "oauth_consumer_key=\"" + OAuthParameters.get("oauth_consumer_key") + "\"" +
",oauth_signature_method=\"" + OAuthParameters.get("oauth_signature_method") + "\"" +
",oauth_timestamp=\"" + OAuthParameters.get("oauth_timestamp") + "\"" +
",oauth_nonce=\"" + OAuthParameters.get("oauth_nonce") + "\"" +
",oauth_version=\"" + OAuthParameters.get("oauth_version") + "\"" +
",oauth_signature=\"" + OAuthParameters.get("oauth_signature") + "\"";
byte[] authEncBytes = Base64.encodeBase64(OAuthHeader.getBytes());
String authStringEnc = new String(authEncBytes);
return authStringEnc;
}
The problem is that
1) while I'm printing the con.getRequestProperty("Authorization") I'm getting a null value which means the Authorization header is not set
2) The final response I'm getting from the server is 403
Any idea what's going wrong here?
I know this might not be an answer but looks like this issue was submitted as a bug to sun and here is the relevant part of the reply.
This behavior is intentional in order to prevent a security hole that
getRequestProperty() opened. setRequestProperty("Authorization")
should still work, you just won't be able to proof the results via
getRequestProperty().
For the original forum post, please see: http://www.coderanch.com/t/205485/sockets/java/setRequestProperty-authorization-JDK
I would not be able to advice why you're getting a 403 but try adding the "Content-Type" request header to your connection and see if it makes any difference. Until I added that header in my code, I was getting a 404 back from the Spring Security module.

Sugar get_entry_list returns "Invalid Session ID" when querying Meetings for a specific user

I try to query Sugar through its REST API using Java for entries in Meetings module for a specific user, namely the one who is logged in currently.
I am trying this a few days already while googling around for asolution.
I made a login() call, where I got a session ID, than I make a call to get_user_id(). With the returned user ID I try to query the Meetings module by using get_entry_list().
To get the Meetings assigned to the UserID it works with following query string, where mUserId holds the returned user id of get_user_id():
queryString = "meetings.assigned_user_id='"+mUserId+"'";
But I not only want to get the meetings, where a user is assigned to, but all Meetings where he participates. For that I try a subquery on meetings_users table in my query.
Here is a query strings I tried, which os working on MySQL prompt. But when I try this over REST, it returns "Invalid Session ID":
queryString = "meetings.id IN ( SELECT meetings_users.meeting_id FROM meetings_users WHERE meetings_users.user_id = '"+mUserId+"' )";
Does anyone have a hint on this? Which conditions lead to an "Invalid Session ID" at all?
What also does not work e.g. is appending "and deleted = '0'" to the first stated query:
queryString = "meetings.assigned_user_id='"+mUserId+"' and deleted = '0'";
also fails.
As requested here is the full code example, platform is Android, API Level 8:
private JSONArray getEntryList(String moduleName,
String selectFields[], String queryString, String orderBy, int max_results) throws JSONException, IOException, KeyManagementException, NoSuchAlgorithmException
{
JSONArray jsoSub = new JSONArray();
if (selectFields.length > 0)
{
for (int i = 0; i < selectFields.length; i++)
{
jsoSub.put(selectFields[i]);
}
}
// get_entry_list expects parameters to be ordered, JSONObject does
// not provide this, so I built my JSON String on my own
String sessionIDPrefix = "{\"session\":\""+ mSessionId+ "\"," +
"\"modulename\":\""+ moduleName+ "\"," +
"\"query\":\""+ queryString + "\"," +
"\"order_by\":\""+ orderBy + "\"," +
"\"offset\":\""+ mNextOffset+ "\"," +
"\"select_fields\":["+ jsoSub.toString().substring(
1, jsoSub.toString().length()-2)+ "\"],"+
"\"max_results\":\""+ 20 + "\"}";
String restData = sessionIDPrefix;
Log.d(TAG, restData);
String data = null;
String baseurl = mUrl + REST_URI_APPEND;
data = httpPost(baseurl+"?method=get_entry_list&input_type=json&response_type=json&rest_data="+restData);
Log.d(TAG, data);
JSONObject jsondata = new JSONObject(data);
mResultCount = jsondata.getInt("result_count");
mNextOffset = jsondata.getInt("next_offset");
return jsondata.getJSONArray("entry_list");
}
private String httpPost(String urlStr) throws IOException{
String urlSplitted [] = urlStr.split("/", 4);
String hostPort[] = urlSplitted[2].split(":");
String hostname = hostPort[0];
int port = 80;
if (hostPort.length > 1)
port = new Integer(hostPort[1]);
String file = "/"+urlSplitted[3];
Log.d(TAG, hostname + ", " + port + ", " +file);
URL url = null;
try {
url = new URL("http", hostname, port, file);
} catch (MalformedURLException e) {
throw new IOException(mContext.getText(R.string.error_malformed_url).toString());
}
Log.d(TAG, "URL "+url.toString());
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
throw new IOException(mContext.getText(R.string.error_conn_creat).toString());
}
conn.setConnectTimeout(60 * 1000);
conn.setReadTimeout(60 * 1000);
try {
conn.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new IOException(mContext.getText(R.string.error_post).toString());
}
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
try {
conn.connect();
} catch (IOException e) {
throw new IOException(mContext.getText(R.string.error_conn_open).toString()
+ "\n" + e.getMessage());
}
int response = 0;
String responseMessage = null;
try {
response = conn.getResponseCode();
responseMessage = conn.getResponseMessage();
} catch (IOException e) {
conn.disconnect();
throw new IOException(mContext.getText(R.string.error_resp_io).toString());
}
Log.d(TAG, "Exception Response "+ response);
if (response != 200) {
conn.disconnect();
throw new IOException(mContext.getText(R.string.error_http).toString()
+ "\n" + response + " " + responseMessage);
}
StringBuilder sb = null;
try {
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
Log.d(TAG,"line " + line);
sb.append(line);
}
rd.close();
} catch (IOException e) {
conn.disconnect();
throw new IOException(mContext.getText(R.string.error_resp_read).toString());
}
conn.disconnect();
if (sb.toString() == null)
{
throw new IOException(mContext.getText(R.string.error_resp_empty).toString());
}
return sb.toString();
}
Calling the code above:
if (login() != OK)
return null;
mResultCount = -1;
mNextOffset = 0;
mUserId = getUserId();
String fields[] = new String [] {
"id",
"name",
"description",
"location",
"date_start",
"date_end",
"status",
"type",
"reminder_time",
"parent_type",
"parent_id",
"deleted",
"date_modified"
};
String queryString = null;
if (syncAllUsers)
queryString = "";
else
{
queryString = "meetings.assigned_user_id = 'seed_sarah_id' and meetings.deleted = '0'";
//queryString = "meetings.id IN ( SELECT meeting_id FROM meetings_users WHERE user_id ='"+mUserId+"'";
}
entryList.clear();
while (mResultCount != 0)
{
if (!seamless_login())
return null;
JSONArray serverEntryList = getEntryList(
"Meetings", fields, queryString, "date_start", 0);
//... do sth with data
}
totalContactsResults += mResultCount;
}
logout();
login() returns valid session id, and getUserId() returns right id. The whole code is already working for fetching contacts, and also working for a simple query as stated above.
Thanks in advance
Marc
After further testing, I realized, that whitespaces in the query string are the problem. They lead to an URL containing whitespace. To avoid that some kind of URL encoding has to be done.
I had not success in encoding the whole URL in my httpPost methods (seems not to be necessary). But replacing spaces with '+' in the query string works for me:
queryString = "meetings.id+IN+(SELECT+meetings_users.meeting_id+FROM meetings_users+WHERE+meetings_users.user_id='"+mUserId+"')";
If anyone has a more elegant method of doing this, please let me know.
You would probably be better off using the get_relationships web service call.
SugarRest.call('get_relationships', [SugarRest.session, 'Users', SugarRest.user_id, 'meetings', '', ['name'], 0, ''])
That should be all you need. In the parameter after 'meetings' you can also pass in an additional filter.

Categories