What I try to do
Hello Guys,
I try to create a login for my server, that I can access the data on it over my app. For this i created a Methode called 'public void doLogin(final String username, final String password)' . In this Methode I start a Thread in which I post the username and password to my server. Now to problem starts. When I do the post my server can't handle my post which looks like this: '"username="+username+"&password="+password'.
To try if its a serverside problem (infact its not) I made a post over 'curl -d' with the same parameters and I get a response without any problems.
For your information the server runs on Ruby3
Question
How do I need to change my Post to the server that it can handle the data I send. By the way the string I post must look exactly like that: '"username="+username+"&password="+password //this means username=LEUSER&password=LEPASS'
Please tell me what I need to change, some code snippets or tutorials would be great. Down here you find the importrent codesnippets of the doLogin Methode
Code
public void doLogin(final String username, final String password) {
Thread t = new Thread() {
public void run() {
String URL = "http://192.168.110.126:3000/sessions.json"; //für momentane testzwecke
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response;
try {
HttpPost post = new HttpPost(URL);
StringEntity se = new StringEntity("username="+username+"&password="+password);
post.setEntity(se);
response = client.execute(post);
if (response != null) {
//response handling
handler.sendEmptyMessage(0);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("DataHandler", "URLConnection-Error" + e);
}
}
};
t.start();
}
Please Guide me Regarding This.
Your code looks like you are sending a html form. In fact curl adds a content-type (with value application/x-www-form-urlencoded) to the http header if you use the -d option.
So try to add the header field like this:
HttpPost post = new HttpPost(URL);
post.addHeader("Content-Type","application/x-www-form-urlencoded");
...
What you need to change is the String entity part. You should change with the following;
ArrayList<NameValuePair> requestParameters = new ArrayList<NameValuePair>();
requestParameters.add(new BasicNameValuePair("username", username));
requestParameters.add(new BasicNameValuePair("password", password));
username & password are the variables that are input on the program.
Lastly, if you forget to set permission it also won't work. You need to set android.permission.INTERNET
Related
I develop an android code for transmit and received between android apps and PHP. The received part which is based on JSON, is properly working. I have tested by set variable manually in PHP code. However, when I have posted the variable from android to php, it cannot receive it. Anyone can tell me the problem ?
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", <Your username here>));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(<Your URL to php file>);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost); // Execute Post to URL
String st = EntityUtils.toString(response.getEntity()); // This is the result from php web
Log.d(TK_Configuration.TAG, "In the try Loop" + st); // Still executing
finalResult = st; // You should register a variable for finalResult;
} catch (Exception e) {
Log.d(TK_Configuration.TAG, "Connection error : " + e.toString());
}
return "OK";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// After that, you will have final result and process to do with it here
// Below is my simple code, please change it
if(finalResult.equals("1")){
Toast.makeText(context, context.getResources().getString(R.string.upload_bike_success), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, context.getResources().getString(R.string.upload_bike_fail), Toast.LENGTH_SHORT).show();
}
// End
}
Please try this, and one more point, you should use Gson library to decode JSON quickly to Java Object after you got JSON string from server.
Note: Replace TK_Configuration.TAG << by your TAG.
you have commented this line it means you are not passing values from Android
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
remove comment from this line.
One more thing, you are passing username but from php you are trying to fetch value as $user = $_POST['name'];, both name must be same.
This question already has answers here:
Send Post request along with HttpHeaders on Android
(2 answers)
Closed 2 years ago.
I could see there are two separate methods in Android docs to post the data and add the headers.
For setting Headers
public void loadUrl (String url, Map<String, String> additionalHttpHeaders)
For setting Post Data
public void postUrl (String url, byte[] postData)
But what I really required is to post the data along with headers. ( Means I want a single method which does both the task ? )
Can somebody please help me out with that.
Thanks :)
I've bumped on same problem recently and after couple of hours solved it.
Here is my code snippet with some comments:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(getPostUrl());
// example of adding extra header "Referer"
httpPost.addHeader("Referer", getReferer());
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
for (PostItem postItem : getPostItems()) {
// key value post pairs
// add post parameters in array list
postParameters.add(new BasicNameValuePair(postItem.getKey(), postItem.getValue()));
}
HttpResponse response = null;
try {
mWebView.getSettings().setJavaScriptEnabled(true);
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
response = httpclient.execute(httpPost);
BasicResponseHandler responseHandler = new BasicResponseHandler();
String htmlString = responseHandler.handleResponse(response);
// important!! is to fill base url
mWebView.loadDataWithBaseURL(getPostUrl(), htmlString, "text/html", "utf-8", null);
} catch (Exception e){
// handle errors
}
It seems that the framework does not provide these features together.
Looking at the source code of WebViewCore (https://android.googlesource.com/platform/frameworks/base/+/eclair-release%5E2/core/java/android/webkit/WebViewCore.java, line 889), additional headers are processed only in the loadUrl call and never in the postUrl.
It has been a while since I programmed for Android and I have lost all my previous work which had the code in it I am having problems with. I am developing an app for both Android and iPhone which connect to the same server to download data. All is well in the iPhone version but on Android when I hit the server with the post data containing the method name I would like to to run on the server it seems that the data is not added to the request.
Why is the POST not working in this request for Android but does for the iPhone version of the app?
Here is the code I am using:
public static void makeRequest() throws Exception {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
HttpEntity entity;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://divisi.co.uk/rest/requesthandler.php");
json.put("method", "getEventListData");
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
entity = response.getEntity();
String retSrc = EntityUtils.toString(entity);
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
if(result.getString("SC") == "200"){
JSONArray data = result.getJSONArray("data");
}
else{
}
} catch(Exception e) {
e.printStackTrace();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
The response I get mack from the server is:
{"data":{"scalar":""},"SC":405,"timestamp":1363788265}
Meaning the method name was not found, i.e. not posted in my request to the server.
heres an example of how i do things like this:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://divisi.co.uk/rest/requesthandler.php");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart(new FormBodyPart("method", new StringBody("getEventListData")));
reqEntity.addPart(new FormBodyPart("NEED_A_KEY_HERE", new StringBody("" + json.toString())));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
JSONObject responseDict = new JSONObject(EntityUtils.toString(response.getEntity()));
allow this is your "http://divisi.co.uk/rest/requesthandler.php" page code, then in android you can use this... you don't allow post in your URL,
use fiddler on your sever side. see if the http message is correct. it seems your sever side problem, can you show us your sever side code which receive and parse json.
If the server can't read your request try to remove:
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
It will use the mime type defaults HTTP.PLAIN_TEXT_TYPE i.e. "text/plain".
I don't see any other possibility, if your code is the one you posted and not a more complicated input JSON object.
Your code to set the POST body may be just fine. I think the problem may be with your web service. Try using something like Rested or curl to manually make the call to your server. I made exactly the same request you are making, including with and without the POST body, and I got the same response from your server:
{"data":{"scalar":""},"SC":405,"timestamp":1365704082}
Some things that may be tripping you up:
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
if(result.getString("SC") == "200"){
JSONArray data = result.getJSONArray("data");
}
Here, you are comparing the string "405" to "200" using ==, when you should first do a null check and then use .equals("200") instead. Or, use result.getInt("SC") == 200 since this is an integer type in your response JSON.
Also, the "data" entity from your server response is not actually coming back as a JSON array. You should use getJSONObject("data") instead.
Additionally, it's always a good idea to externalize your strings.
Here's how the code should look:
public static final String JSON_KEY_SC = "SC";
public static final String JSON_KEY_DATA = "data";
...
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
String sc = result.getString(JSON_KEY_SC);
if (sc != null && sc.equals("200")) {
JSONObject data = result.getJSONObject(JSON_KEY_DATA);
}
else {
...
}
Hi I'm about to perform an HTTP request to add some data to a local data base using wampserver, so I've made a button andh within that button i will perform that action , but the problem is that i can't connect to the data base !!!
this is the message apperas on the toast "android.os.networkonmainthreadexception"
and this is my code ---> http://pastebin.com/TsQ7NbNm
============================
I'm Newer to Android Programming so please Help me !
You cannot make http request on your UI thread. Consider using AsyncTask or some other method of asynchronuos call.
Upto the API level-10 it is fine to make http request on UI thread. But from API-11, any task that takes long time to complete must be done on background task. The reason behind this is any task that takes 5 seconds or more on UI thread then ANR(Application Not Responding) i.e. force close happens. To do that we have create some background thread or simply make use of AsyncTask.
if you want to post data on your server then you need to well design server for post data. recent my server configuration i post data by using this code and well performed.
Button send = (Button) findViewById(R.id.send_sms);
send.setOnClickListener(this);
public void onClick(View v)
{
switch (v.getId())
{
case R.id.send_sms:
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://10.0.2.2/folder/saver.php";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cell", "+8801899999"));
params.add(new BasicNameValuePair("pin", "1234"));
params.add(new BasicNameValuePair("msg", "hi!"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
showAlert(EntityUtils.toString(resEntity));
//Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
you can try this way.if your server has password then give it.
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$valeur1=$_REQUEST['valeur1'];
$valeur2=$_REQUEST['valeur2'];
$req=mysql_query("insert into testapp (valeur1,valeur2) values('$valeur1','$valeur2')");
if($req)
echo "ok";
else
echo "erreur";
;
?>
I'm trying to increase my knowledge to Android and trying to code a small app for my personal needs.
I'm trying to post data via the HTTP Post method on a test server.
The request is sent ok, but now, I'm trying to display the response, which is an HTML page with the dump of my request.
Here is an extract of my code, it is basically a few EditText fields, and button that sends the request.
The following code is the listener for that button.
validateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://posttestserver.com/post.php?dump&html&dir=mydir&status_code=200");
try {
// Gathering data
String value01 = nb01Spinner.getSelectedItem().toString();
String value02 = nb02EditText.getText().toString();
String value03 = nb03EditText.getText().toString();
String value04 = nb04EditText.getText().toString();
// Add data to value pairs
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(04);
nameValuePairs.add(new BasicNameValuePair("test01", value01));
nameValuePairs.add(new BasicNameValuePair("test02", value02)); //
nameValuePairs.add(new BasicNameValuePair("test03", value03));
nameValuePairs.add(new BasicNameValuePair("test04", value04));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I'm not sure if I need to create another Activity or not... I suppose I also have to create a webview aswell, but I'm a bit lost. For now the "raw" HTML would be fine, but afterwards I will need to parse the data, and extract only the strings I need.
So I would need help (an a good and simple example !)
Thank you.
String ret = EntityUtils.toString(response.getEntity());
Maybe this will help?
Very simple approach is Take textview the way you have taken button widget. and what ever response you got set in the textview. you will be able to see the response. else use the Log to log your response in the logcat.
This is how you get the Http response :
byte[] buffer = new byte[1024];
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.booom.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("params","1"));
//.......
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
buffer = EntityUtils.toString(response.getEntity()).getBytes();
I am using:
Log.d("log_response", response.getStatusLine().toString());