Problem on my part is solved
The owner of the server removed some code to check if the basics of sending a POST/GET method works and that works perfectly.
I'm still dont know what the problem is, but it sure is not my problem lol
I'm trying to send POST method to the server, but it turns out the server gets a GET method instead. We got it working on the iphone so the server is correct.
This is the code I written to send data:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myurl.nl/casus");
httppost.setHeader("Authorization", "xxxxxxxxxxxxxxx");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//casus
nameValuePairs.add(new BasicNameValuePair("casusid", casus.id+""));
String woorden = "[";
for(int i = 0; i < words.length; i++){
woorden += "\""+words[i]+"\"";
if(i != words.length-1){
woorden += ",";
}
}
woorden += "]";
nameValuePairs.add(new BasicNameValuePair("woorden", woorden));
//info
SharedPreferences sharedPref = getSharedPreferences("omapp", MODE_PRIVATE);
String age = sharedPref.getString("age", "");
String sex = sharedPref.getString("sex", "");
nameValuePairs.add(new BasicNameValuePair("leeftijdscategorie", age));
nameValuePairs.add(new BasicNameValuePair("geslacht", sex));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d("json", responseBody);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
PHP code:
// Service token authorization.
require_once('../classlib/Auth.php');
$auth = new Auth;
if ( !$auth->valid() ) {
header('HTTP/1.1 401 Unauthorized');
exit;
}
// Setup casussen.
require_once('../classlib/PDOFactory.php');
require_once('../classlib/Casussen.php');
$casussen = new Casussen;
$casussen->setPDO(PDOFactory::create());
$rs = (object) array();
switch ( $_SERVER['REQUEST_METHOD'] ) {
case 'GET': {
mail('sdgsdgsdg#gmail.com', 'The get method was called', print_r($_SERVER,1));
$fromcasusid = !empty($_GET['fromcasusid']) ? (int) $_GET['fromcasusid'] : null;
$rs->casussen =$casussen->get($fromcasusid);
break;
}
case 'POST': {
mail('jsdgsdgsn#gmail.com', 'The post method was called', print_r($_SERVER,1));
$casusreactie = json_decode(file_get_contents("php://input"));
try {
$casussen->post($casusreactie);
} catch ( Exception $e ) {
$rs->error = (object) array(
'code' => $e->getCode(),
'message' => $e->getMessage(),
);
}
break;
}
default: {
header('HTTP/1.1 405 Method Not Allowed');
exit;
}
} // switch
header('Content-type: application/json; charset=utf-8');
exit(json_encode($rs));
One workout..
call doPost method from inside your doGet
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException{
doPOst(request, response)
}
I was also having a similar issues.
I was able to fix it by add "www." to the url.
But i would like to know how that is making a difference, I had successfully tested the server handling with a jQuery ajax request without the "www." .
Related
Am trying to create user into my salesforce account through REST api using java.But its returning 400 status code.Can you please guide me?
Here is the code am trying:
public static void createUsers() {
System.out.println("\n_______________ USER INSERT _______________");
String uri = baseUri + "/sobjects/User/";
System.out.println(uri);
try {
//create the JSON object containing the new lead details.
JSONObject lead = new JSONObject();
lead.put("FirstName", "Jake");
lead.put("LastName", "sully");
lead.put("Alias", "Jake");
lead.put("Email", "Jake#gmail.com");
lead.put("Username", "Jake#gmail.com");
lead.put("Name", "jake");
lead.put("UserRoleId","00E28000000oD8EEAU");
lead.put("Id", "10028000000GLSIAA4");
lead.put("EmailEncodingKey", "ISO-8859-1");
lead.put("TimeZoneSidKey", "Asia/Kolkata");
lead.put("LocaleSidKey", "en_US");
lead.put("ProfileId", "00e280000027hnGAAQ");
lead.put("LanguageLocaleKey", "en_US");
//Construct the objects needed for the request
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(oauthHeader);
httpPost.addHeader(prettyPrintHeader);
// The message we are going to post
StringEntity body = new StringEntity(lead.toString(1));
body.setContentType("application/json");
httpPost.setEntity(body);
//Make the request
HttpResponse response = httpClient.execute(httpPost);
//Process the results
System.out.println(response.toString());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 201) {
String response_string = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(response_string);
// Store the retrieved lead id to use when we update the lead.
leadId = json.getString("id");
} else {
System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
}
} catch (JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}
i am new to android and i am working on one application ,In which i have to add books by posting all book details to pHp server,here i am using httpPost call to send all book details,but in pHp server there is a line,
$this->get('security.context')->getToken()->getUser()
i cannot able to call it simply by httpPost in android..so i really need help to solve this problem..so please help me how to call it in android..thanks in advance....
this is the httppost used to send book details..
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("www.example.com");
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("book", "name"));
nameValuePair.add(new BasicNameValuePair("price", "rate"));
nameValuePair.add(new BasicNameValuePair("author","author"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
}
this is the php post function
public function handlePOST($params, Request $request) {
$book = new Book();
if (isset($params['isbn'])) {
$book->setIsbn($params['isbn']);
}
$book->setTitle($params['title']);
if (isset($params['type'])) {
$book->setFrequency($params['type']);
}
if (isset($params['period'])) {
$book->setPeriod($params['period']);
}
if (isset($params['frequency'])) {
$book->setFrequency($params['frequency']);
}
if (isset($params['type'])) {
$book->setType($params['type']);
}
if (isset($params['author'])) {
$book->setAuthor($params['author']);
}
if (isset($params['lang'])) {
$book->setLang($params['lang']);
}
if (isset($params['pages'])) {
$book->setPages($params['pages']);
}
if (isset($params['price'])) {
$book->setPrice($params['price']);
}
if (isset($params['status'])) {
$book->setStatus($params['status']);
} else {
$book->setStatus(1);
}
if (isset($params['bookCondition'])) {
$book->setBookCondition($params['bookCondition']);
}
//$book->setAvailableFor($params['availableFor']);
if (isset($params['description'])) {
$book->setDescription($params['description']);
}
if (isset($params['genre'])) {
$book->setGenre(json_encode($params['genre']));
}
// $repository = $this->getDoctrine()->getRepository('UserBundle:User');
// $user = $repository->findOneBy(
// array('id' =>$params['userid'])
// );
//how to call below code
$user = $this->get('security.context')->getToken()->getUser();
$user->setRewardPoints($user->getRewardPoints() + 10);
$book->setCreatedBy($user->getId());
$em = $this->getDoctrine()->getEntityManager();
$em->persist($book);
$em->flush();
// $this->triggerBookChange($book->getTitle(), $params['type']);
$response = new Response(json_encode($params));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
I am creating my first android which will take data from a signup form and send it to a php backend.
The php backend will take the data and save in a database and give a jason encoded message telling if it is success or not.
Now I want to eliminate the possibility of dupilicate usernames so when the android app sends data to the php backend I will first check and if it is duplicate I will throw an error message like this
$response["error"] = true;
$response["message"] = "Username Already taken";
echoRespnse(400,$response);
On Success the backend will send something like this
$response["error"] = false;
$response["message"] = "Successfuly Registered";
echoRespnse(201,$response);
How do I enable the android app to read this info and understand if the user was created or an error occured.
My current Android signup.java code looks like this
public void post() throws UnsupportedEncodingException
{
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
if (password.equals(confirmpass)) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
//Code to check if user was successfully created
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}
I think you want help to get and read the JSON data provided by your service, right?
In your SignUp Activity create an AsyncTask because you can not perform this on the main thread.
private class DownloadOperation extends AsyncTask<Void, Void, String> {
String uname = "";
String email = "";
String password = "";
String confirmpass = "";
String phone = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
}
#Override
protected String doInBackground(Void... params) {
String response = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
httpResponse = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("tag", "Result:\n" + result);
}}
And then call
// Calling async task to get json
new DownloadOperation().execute();
And you will see the json string printed on your Console :)
To get an JSONObject using the response String:
JSONObject jsonObj = new JSONObject(STRING);
Hope that helps.
You could make your "error" an int instead of a boolean, and have your php backend return specific error codes. This would allow your android application to understand the specific error. Without this kind of modification, checking the value of message for a specific string is another option.
For example, you could return 0 if there was no error, 1 if the username was already taken, 2 if .. etc.
BEFORE registering the user and inserting into database ,check the query for username in database..and if user name found then encode json value as error
$query=mysql_query("select id from yourtable where username ='$username'");
If(mysql_numnum_rows($query)>0)
// example for response
//responses from server for success
response["success"]=1;
response["message"]='No error code'
//responses from server for duplicate username
response["success"]==0
response["message"]='Username exists';
// java code
// after getting string from server parse in into json object
JSONObject jsonObj = new JSONObject(STRING);
int success = jsonObj.getInt("success");
message = jsonObj.getString("message");
if (success == 1) {
// register successfully
} else {
// username already exist
}
I have tried different methods to upload and retrieve a link via imgur but none have been successfull despite looking at the imgur api.
http://api.imgur.com/examples#uploading_java
But the following methods partly works..
im trying to retrieve,
errors: if any errors occured.
link to image: the link to the image hosted
delete link: the link to delete the image hosted
But i only end up with the "delete link", as the others are blank,
check it out:
public void post(String path) {
List<NameValuePair> postContent = new ArrayList<NameValuePair>(2);
postContent.add(new BasicNameValuePair("key", DEV_KEY));
postContent.add(new BasicNameValuePair("image", path));
String url = "http://api.imgur.com/2/upload";
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < postContent.size(); index++) {
if(postContent.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(postContent.get(index).getName(), new FileBody(new File (postContent.get(index).getValue())));
} else {
// Normal string data
entity.addPart(postContent.get(index).getName(), new StringBody(postContent.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
mImgurResponse = parseResponse (response);
Iterator it = mImgurResponse.entrySet().iterator();
while(it.hasNext()){
HashMap.Entry pairs = (HashMap.Entry)it.next();
Log.i("INFO",pairs.getKey().toString());
if(pairs.getValue()!=null){
reviewEdit.setText(pairs.getValue().toString());
Log.i("INFO",pairs.getValue().toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private Map<String,String> parseResponse(HttpResponse response) {
String xmlResponse = null;
try {
xmlResponse = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (xmlResponse == null) return null;
HashMap<String, String> ret = new HashMap<String, String>();
ret.put("error", getXMLElementValue(xmlResponse, "error_msg"));
ret.put("delete", getXMLElementValue(xmlResponse, "delete_page"));
ret.put("original", getXMLElementValue(xmlResponse, "original_image"));
return ret;
}
private String getXMLElementValue(String xml, String elementName) {
if (xml.indexOf(elementName) >= 0)
return xml.substring(xml.indexOf(elementName) + elementName.length() + 1,
xml.lastIndexOf(elementName) - 2);
else
return null;
}
All i get back in the end is a hashmap mImageResponse with only the delete link...
any ideas on what im doing wrong?
The fix to this was merely to change the URL to: imgur.com/api/upload.xml
I've written some code for my Android device to login to a web site over HTTPS and parse some data out of the resulting pages. An HttpGet happens first to get some info needed for login, then an HttpPost to do the actual login process.
The code below works great in a Java project within Eclipse which has the following JAR files on the build path: httpcore-4.1-beta2.jar, httpclient-4.1-alpha2.jar, httpmime-4.1-alpha2.jar, and commons-logging-1.1.1.jar.
public static MyBean gatherData(String username, String password) {
MyBean myBean = new MyBean();
try {
HttpResponse response = doHttpGet(URL_PAGE_LOGIN, null, null);
System.out.println("Got login page");
String content = EntityUtils.toString(response.getEntity());
String token = ContentParser.getToken(content);
String cookie = getCookie(response);
System.out.println("Performing login");
System.out.println("token = "+token +" || cookie = "+cookie);
response = doLoginPost(username,password,cookie, token);
int respCode = response.getStatusLine().getStatusCode();
if (respCode != 302) {
System.out.println("ERROR: not a 302 redirect!: code is \""+ respCode+"\"");
if (respCode == 200) {
System.out.println(getHeaders(response));
System.out.println(EntityUtils.toString(response.getEntity()).substring(0, 500));
}
} else {
System.out.println("Logged in OK, loading account home");
// redirect handler and rest of parse removed
}
}catch (Exception e) {
System.out.println("ERROR in gatherdata: "+e.toString());
e.printStackTrace();
}
return myBean;
}
private static HttpResponse doHttpGet(String url, String cookie, String referrer) {
try {
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
HttpGet httpGet = new HttpGet(url);
httpGet.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
httpGet.setHeader(HEADER_USER_AGENT,HEADER_USER_AGENT_VALUE);
if (referrer != null && !referrer.equals("")) httpGet.setHeader(HEADER_REFERER,referrer);
if (cookie != null && !cookie.equals("")) httpGet.setHeader(HEADER_COOKIE,cookie);
return client.execute(httpGet);
} catch (Exception e) {
e.printStackTrace();
throw new ConnectException("Failed to read content from response");
}
}
private static HttpResponse doLoginPost(String username, String password, String cookie, String token) throws ClientProtocolException, IOException {
try {
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
HttpPost post = new HttpPost(URL_LOGIN_SUBMIT);
post.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
post.setHeader(HEADER_USER_AGENT,HEADER_USER_AGENT_VALUE);
post.setHeader(HEADER_REFERER, URL_PAGE_LOGIN);
post.setHeader(HEADER_COOKIE, cookie);
post.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("org.apache.struts.taglib.html.TOKEN", token));
formParams.add(new BasicNameValuePair("showLogin", "true"));
formParams.add(new BasicNameValuePair("upgrade", ""));
formParams.add(new BasicNameValuePair("username", username));
formParams.add(new BasicNameValuePair("password", password));
formParams.add(new BasicNameValuePair("submit", "Secure+Log+in"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams,HTTP.UTF_8);
post.setEntity(entity);
return client.execute(post);
} catch (Exception e) {
e.printStackTrace();
throw new ConnectException("ERROR in doLoginPost(): "+e.getMessage());
}
}
The server (which is not under my control) returns a 302 redirect when the login was successful, and 200 if it fails and re-loads the login page. When run with the above JAR files I get the 302 redirect, however if I run the exact same code from an Android project with the 1.6 Android JAR file on the build path I get the 200 response from the server. I get the same 200 response when running the code on my 2.2 device.
My android application has internet permissions, and the HttpGet works fine. I'm assuming that the problem lies in the fact that HttpPost (or some other class) is different in some significant way between the Android JAR version and the newer Apache versions.
I've tried adding the Apache libraries to the build path of the Android project, but due to the duplicate classes I get messages like: INFO/dalvikvm(390): DexOpt: not resolving ambiguous class 'Lorg/apache/http/impl/client/DefaultHttpClient;' in the log. I've also tried using a MultipartEntity instead of the UrlEncodedFormEntity but I get the same 200 result.
So, I have a few questions:
Can I force the code running under Android to use the newer Apache libraries in preference to the Android versions?
If not, does anyone have any ideas how can I alter my code so that it works with the Android JAR file?
Are there any other, totally different approaches to doing an HttpPost in Android?
Any other ideas?
I've read a lot of posts and code, but I'm not getting anywhere.
I have now given up on getting the HttpClient route to give the expected response from the server when run on Android. Instead I rewrote the doPost method above to use an HttpsURLConnection instead. Here's the new (working) version in the hope that it's useful to someone.
private static LoginBean altPost(String username, String password, String cookie, String token){
LoginBean loginBean = new LoginBean();
HttpsURLConnection urlc = null;
OutputStreamWriter out = null;
DataOutputStream dataout = null;
BufferedReader in = null;
try {
URL url = new URL(URL_LOGIN_SUBMIT);
urlc = (HttpsURLConnection) url.openConnection();
urlc.setRequestMethod("POST");
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
urlc.setRequestProperty(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE_FF);
urlc.setRequestProperty("Cookie", cookie);
urlc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
String output = "org.apache.struts.taglib.html.TOKEN="+ URLEncoder.encode(token, HTTP.UTF_8)
+"&showLogin=true&upgrade=&username="+ URLEncoder.encode(username, HTTP.UTF_8)
+"&password="+ URLEncoder.encode(password, HTTP.UTF_8)+"&submit="
+URLEncoder.encode("Secure+Log+in", HTTP.UTF_8);
dataout = new DataOutputStream(urlc.getOutputStream());
// perform POST operation
dataout.writeBytes(output);
// get response info
loginBean.setResponseCode(urlc.getResponseCode());
// get required headers
String headerName = null;
StringBuffer newCookie = new StringBuffer(100);
String redirectLocation = "";
for (int i=1; (headerName = urlc.getHeaderField(i)) != null;i++) {
if (headerName.indexOf(COOKIE_VALUE_SESSION) > -1) {
if (newCookie.length() > 0) {newCookie.append("; ");}
newCookie.append(headerName);
}
if (headerName.indexOf(COOKIE_VALUE_AUTH) > -1) {
if (newCookie.length() > 0) {newCookie.append("; ");}
newCookie.append(headerName);
}
if (headerName.indexOf("https://") > -1) {
redirectLocation = headerName;
}
}
loginBean.setCookie(newCookie.toString());
loginBean.setRedirectUrl(redirectLocation);
in = new BufferedReader(new InputStreamReader(urlc.getInputStream()),8096);
String response;
// write html to System.out for debug
while ((response = in.readLine()) != null) {
System.out.println(response);
}
in.close();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return loginBean;
}
I still have no idea why the HttpClient way didn't work properly.
To avoid the collisions, use this JAR file for httpclient:
httplib
And this post would also be very useful:
An answer to Stack Overflow question Apache HTTP client or URLConnection
Is it possible that this website does user-agent detection and actually returns different results because it's Android? Given that 200 implies success, why must it give a 302 instead of a 200? Have you printed out the result that you get when it returns a 200, and does it give any additional information?
Check the RedirectHandler, override the default one and do some logging in it, I had problems with that when going to Android...