For anyone who might need help creating a Drupal user from an Android app, the following code works:
//create a new HttpClient and post header
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://test.site.com/testpoint/user/register");
// TODO Auto-generated method stub
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add( new BasicNameValuePair("account[pass]", "cutelady"));
nameValuePairs.add( new BasicNameValuePair("account[mail]", "scarter#sgc.gov"));
nameValuePairs.add( new BasicNameValuePair("account[name]", "Samantha Carter"));
httpPost.setEntity( new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
}catch(Exception e){
Log.e("HTTP ERROR", e.toString());
}
However, I have an additional problem: when using the profile module to provide additional custom CCK fields for the user registration process, I can't find the right account[cck_parameter] to connect and save my Android data to the profile CCK field.
What can I try to resolve this?
User is a user object and extra profile values are node objects. So the user_save function is designed to accept few params.
The key is, you can create user profiles overriding "required field" status of the user/register form.
Keep the current form, and try to create a new node too, after saving the user object.
See content profile API to see how to save(it's a node_save() ) a content profile.
Related
I am posting a url with params containg an underscore (_).
sample: http://sdsdsds_asasasahjhd.com/dsdsdsd/login.json?
I am posting it like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://sdsdsds_asasasahjhd.com/dsdsdsd/login.json?");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key1", "value1"));
nameValuePairs.add(new BasicNameValuePair("key2", "value2"));
nameValuePairs
.add(new BasicNameValuePair("key3", "value3"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
}
When I am inspecting httpclient.execute(httppost) I am getting IllegalArgumentException and in catch in exception details it is telling Host name cannot be null.
Please specify any solution.
I have gone through some other questions here:
java.lang.IllegalStateException: Target host must not be null, or set in parameters
Host name may not be null in HttpResponse execute for android
but no use as I am not encoding the whole url.
I have an open-source library with network implementation mechanism. It has just receiver an workaround implementation. All you need it to set the host by reflection in case of troubles:
final URI uriObj = new URI("https", host, path, null, null);
if (uriObj.getHost() == null) {
final Field hostField = URI.class.getDeclaredField("host");
hostField.setAccessible(true);
hostField.set(uriObj, host);
}
return uriObj;
The commit is here.
well it clearly states that the host name can not be null.. your url doesn't specify one..
a url is expected to be in the format
http://hostName.com/example..../example.json
HttpPost httppost = new HttpPost(String);
This contructor will attempt to form a URL instance from the provided String. If this fails, you'll be dealing with a null value.
Please post the actual URL you're using and not a sample if you want us to be able to help you further.
See this link. Apache doesnt support underscore. You should change the url
https://issues.apache.org/jira/browse/HTTPCLIENT-911
So i'm a web developer by trade but am making an app at the moment.
I've got a program on my PC which sends data from my PC to a database on my webhost.
What I'm after now, is to create an app that is able to download that data with a series of queries.
Are there any good resources around that would help me to develop some Java code, to connect to a server through my tablet when I'm out and about and download the information from my webhost when on a different wifi network?
Thanks chaps, any help is appreciated.
The way I handle it is that I just create a web page based on what I want to do. For example if I want to verify a login on an app I create a page that takes in a username and password.
On the device I just post the username and password values by using a HTTP post transaction.
Example:
public boolean LoginUser()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your URL comes here...");
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
DataCrypt crypt = new DataCrypt();
try
{
this.Cryptemail = crypt.bytesToHex(crypt.encrypt(this.Email));;
this.Cryptpass = crypt.bytesToHex(crypt.encrypt(this.Password));
}
catch (Exception e)
{
DebugLog.log(e.getMessage());
}
nameValuePairs.add(new BasicNameValuePair("Password", this.Cryptpass));
nameValuePairs.add(new BasicNameValuePair("Mail", this.Cryptemail));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
BasicHttpResponse response = (BasicHttpResponse) httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String response = EntityUtils.toString(entity);
return true;
}
catch (Exception e)
{
DebugLog.log(e.getMessage());
return false;
}
return false;
}
EDIT: So you can just make a page that takes in some parameters that you want to base your query on and return the result in some way (for example by XML).
Hope this helps you out! :)
I was able log in through my android app to http://yearbook08.com/ using this code:
String URL="http://yearbook08.com/login.php";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userId", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now when I move to another activity I want to retrieve http://yearbook08.com/wall.php but the web server does not recognize my last login and asks me to login again.
Is there a way that I can stay logged in after once logging in? Kindly help !
Your code does not take into account session management. This happening as after a successful login no cookies are set, so if you send another request the initial authentication is lost and server takes it to be a fresh request.
I would suggest you use Apache httpcomponents library 4.x (httpclient in particular)
Create a httpcontext and attach a cookie store as
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet("http://www.google.com/");
// Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget, localContext);
Make use the same localContext in the subsequent requests. Also note cookiestore and httpcontext should be declared as static or global variables as their scope must exist wherever you carry the httprequest. You don't have to set cookies on your own, it is automatically done!
And do read about HttpComponents 4.x http://hc.apache.org/httpcomponents-client-ga/index.html
Update 1:
Make sure it is v4 and v3. basicCookiestore has only been present since v4. It is clear now that you are using v3 which does not know about basiccookiestore object. Add the v4 library to your project. It will solve your problem
Update 2
If you try to retrieve http://yearbook08.com/wall.php from the 2nd activity this problem will arise as the 2nd activity won't have httpcontext,httpclient or the Cookiestore object in it. So it will send a fresh request.
1st approach
So you should try to fetch the contents you need in the first activity itself and then pass on the fetched data to the 2nd activity. This way you'll have session maintained.
2nd soln
If you are not satisfied with this you can check this out http://www.jameselsey.co.uk/blogs/techblog/android-implementing-global-state-share-data-between-activities-and-across-your-application/ Share httpcontext, cookiestore and httpclient across the activities to accomplish the task.
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());
I am new to the client-server side programming so my question might be basic.
Basically, I am trying to send data in JSON format from android to a Django server. The code for sending the data is the following:
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8000/androidweb/edit/");
JSONObject j = new JSONObject();
try {
j.put("name", "cdfe");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nameValuePairs.add(new BasicNameValuePair("year", j.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}catch(Exception e) {
//catch the exception and print it
}
So my intention is to basically call the url mentioned in code. I added the url to Django urls.py so I can use the views.py class to store the JSON data I entered above in a sqlite database table, which contains only one field called "name". However, I don't know if my approach is right. Most code samples I have seen pass the data to a php file, so I was wondering if it is possible to do it through a python class, views.py?
If it is possible, can you please give me a code sample to be implemented in "views.py" of how to capture JSON data sent from the above code and store it in a table with a "name" field?
Thanks!
Data sent via POST is available via request.POST. Try examining request.POST['year'].