Android httpclient (request) encoding problem - android

Hi
I am trying to build a little rest client in android. I simply tries to obtain an xml file which can be parsed later on. However I have some encoding problems.
Special characters like ø and å are not recognized. The xml file uses ISO-8859-1 encoding but i cannot really figure out how to force the httpclient to use this encoding. Anyone that is able to help?
Here is the code:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
String URL = "http://konkurrence.rejseplanen.dk/bin/rest.exe";
String result = "";
Button btn;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tvResponse);
btn = (Button)findViewById(R.id.btnMakeRequest);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String query = "/departureBoard?id=8600626&date=19.03.11&time=07:02&useBus=0";
callWebService(query);
}
});
}
public void callWebService(String q){
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL + q);
ResponseHandler<String> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
tv.setText(result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
Log.i("test", result);
}
}
thanks in advance.
best regards, kenneth

I would take a look at the response's headers. The response will need to set :
Content-Type: text/xml; charset:ISO-8859-1;
Otherwise, my understanding is that the http client will default encode to utf-8. You may also need to adjust the header on your request if your web service is using it to try and determine what you want. The thing to know is, if you do this in a browser do you get back the iso document or a utf-8 one?
HTTPGet extends this class with header methods
Source info on xml encoding

Related

How to login and keep cookie for later use of a webpage

So, I have this webpage which I want to access, but first I have to login from another webpage. I want to keep the cookies and then use it for later automatic login. So far what I did:
First, this is the login webpage: https://autenticacao.uvanet.br/autenticacao/pages/login.jsf
It's my university's student's area.
public class Consulta extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
StringBuilder builder = new StringBuilder(100000);
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urls[0]);
try {
List<NameValuePair> val = new ArrayList<NameValuePair>(2);
val.add(new BasicNameValuePair("form:usuario", "myusername"));
val.add(new BasicNameValuePair("form:senha", "mypass"));
httpPost.setEntity(new UrlEncodedFormEntity(val));
HttpResponse response = client.execute(httpPost);
InputStream content = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
builder.append(s);
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.toString();
}
}
This is the class I use to make the HttpPost and this is how I call it:
#Override
public void onClick(View v) {
try{
String html = new Consulta().execute("https://autenticacao.uvanet.br/autenticacao/pages/login.jsf").get();
Document doc = Jsoup.parse(html);
Element link = doc.select("title").first();
String t = link.text();
tv1.setText(t);
}catch(Exception e){
e.printStackTrace();
}
}
I believed it would work this way:
I send the webpage to login to Consulta.java
The class would get the fields "form:usuario" and "form:senha" and fill them with myusername and mypassword and then login
The class would return me html code of the second webpage as string
But what happens is that it returns me the first webpage (the login one). I'm pretty sure I'm doing something wrong, but I don't know what, could someone help me? Also, sorry for my english, it's not my main language.
When you do the login (in https://autenticacao.uvanet.br/autenticacao/pages/login.jsf), I don't think the response is the html code of the second webpage. Are you sure about this?
I think the normal behavior for a login page is to respond with the same page (the login one) but adding the session cookie and the header to do a redirect to the second webpage, but not the second page itself.
In this case, you have to read the http header response to extract these parameters: the cookies and the URL of the second webpage.
Using the object HttpResponse:
Header[] h = response.getAllHeaders();
But I recommend you to use HttpURLConnection class instead of DefaultHttpClient.

Android : How to access web page and send parameters to it

I am developing an android application and i need to access the server side which is done as web pages in asp.net
below is the web page URL :
theWebPageURL?action=methodName&email=theEmail
i don't know what methods shall i use to access this URL and send the email parameter to it and get the response.
i searched alot and none worked
can anyone help me please ?
I would recommend reviewing these two similar qustions:
Make an HTTP request with android
How to add parameters to a HTTP GET request in Android?
UPDATE
The below code is a working sample I put together based off of the answers in the two links above; if this helps you, be sure to thank them.
For demonstration, the uri in this sample is being constructed into http://www.google.com/search?q=android.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Construct the URI
String uri = "http://www.google.com/search?";
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("q", "android"));
uri += URLEncodedUtils.format(params, "utf-8");
// Run the HTTP request asynchronously
new RequestTask().execute(uri);
}
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// result contains the response string.
}
}
}
And, of course, don't forget to add this to your manifest:
<uses-permission android:name="android.permission.INTERNET" />
You need to use http get request
HttpGet
and add this line to your manifest file
<uses-permission android:name="android.permission.INTERNET" />
also, check this link

How to Authenticate android app with tomcat sever?

I am working on an application where I want to send an HTTP post to my Tomcat sever. In this post,I want to send the user-id as well as password and after successful authentication from TomCat it will respose to my app, I
I want next-page to display in my emulator?
Any procedure or framework on this aspect ...that I have to use.
I am posting the code to post the request and get response.
public class Register extends Activity
{
public static final String PREFS_NAME = "LoginPrefs";
public static final String USER_NAME = "USER";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
TextView txt = (TextView) findViewById(R.id.textView1);
txt.setText(getPage());
}
private String getPage()
{
String str = "***";
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.yahoo.com");
HttpResponse rp = hc.execute(post);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return str;
}
}
Now u help me with how to send data with request and server will check the incoming data if data is present in database that will ensure that user is a valid user and send some response depending on that response i will navigate to next page.
How will do this? Please help since i am new to java and android.
take a look at this first response from a google search here

problem on sending file to server in android..formated code

public class Sendfile extends Activity
{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String url = "http://http://192.168.0.158:4299";
File file = new File(Environment.getExternalStorageDirectory(),
"sendingfile.txt");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
// Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Toast.makeText(getApplicationContext(), response.toString(),
Toast.LENGTH_LONG).show();
// Do something with response...
} catch (Exception e) {
// show error
}
}
}
Your first issue is that your URL is invalid; instead of "http://http://192.168.0.158:4299" it should read "http://192.168.0.158:4299". There may well be more problems in there as well, but that one leaps off the page.
The style of the code is pretty horrible as well. A large block of code that catches Exception is almost always bad. A large block of code that catches Exception and then ignores it is almost always worse.

Submit form with POST data in Android app

I've been searching the web for a way to do this for about a week now, and I just can't seem to figure it out.
I'm trying to implement an app that my college can use to allow users to log in to various services on the campus with ease. The way it works currently is they go to an online portal, select which service they want, fill in their user name and pwd, and click login. The form data is sent via post (it includes several hidden values as well as just the user name and pwd) to the corresponding login script which then signs them in and loads the service.
I've been trying to come at the problem in two ways. I first tried a WebView, but it doesn't seem to want to support all of the html that normally makes this form work. I get all of the elements I need, fields for user and pwd as well as a login button, but clicking the button doesn't do anything. I wondered if I needed to add an onclick handler for it, but I can't see how as the button is implemented in the html of the webview not using a separate android element.
The other possibility was using the xml widgets to create the form in a nice relative layout, which seems to load faster and looks better on the android screen. I used EditText fields for the input, a spinner widget for the service select, and the button widget for the login. I know how to make the onclick and item select handlers for the button and spinner, respectively, but I can't figure out how to send that data via POST in an intent that would then launch a browser. I can do an intent with the action url, but can't get the POST data to feed into it.
So here is what I have right now...
HttpParams params = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(action);
String endResult = null;
try
{
post.setEntity(new UrlEncodedFormEntity(myList));
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
String response = client.execute(post, new BasicResponseHandler());
endResult = response;
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
So my question now... is how do I take the endResult screen, which should be the page returned after I logged in to my service, and display it in a browser?
What's wrong with them just using the built in browser? You can also submit a form using UrlEncodedFormEntity and HttpClient.
HttpParams params = new DefaultHttpParams(); // setup whatever params you what
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost("someurl");
post.setEntity(new UrlEncodedFormEntity()); // with list of key-value pairs
client.execute(post, new ResponseHandler(){}); // implement ResponseHandler to handle response correctly.
Okay and after you have the response in a string. The response since its a page is going to be in html. You need to use a WebView to show the html. WebView has a method loadData() that takes a string of html and displays it.
Based on #RobbyPonds answer, for the benefit of people wandering past here, below is a generic implementation to post and receive a response from a URI (NOTE Also contains waiting implementation to return a response, probably not every day implementation of network call):
private static String responseValue;
#SuppressWarnings({ "unchecked", "rawtypes" })
public static String sendPostToTargetAndWaitForResponse() throws ClientProtocolException, IOException {
final Thread currentThread = Thread.currentThread();
synchronized (currentThread) {
HttpParams params = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(HTTP_POST_URI);
// List Creation with post data for UrlEncodedFormEntity
ArrayList<NameValuePair> mList = new ArrayList<NameValuePair>();
mList.add(new NameValuePair() {
#Override
public String getValue() {
return getSampleJSON();
}
#Override
public String getName() {
return "json";
}
});
post.setEntity(new UrlEncodedFormEntity(mList)); // with list of key-value pairs
client.execute(post, new ResponseHandler(){
#Override
public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
responseValue = EntityUtils.toString(response.getEntity(), "UTF-8");
synchronized (currentThread) {
currentThread.notify();
}
return null;
}
});
try {
currentThread.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return responseValue;
}
}

Categories

Resources