This question already exists:
send post android to php not working [closed]
Closed 9 years ago.
I have a problem I want to send
Email and the name and phone to the server php at the same time
Is there a solution
On which I work is at the bottom
........................................................
public class MainActivity extends Activity {
EditText name;
EditText email;
EditText tlf;
Button btn;
string resultat=null;
InputStream is = null;
StringBuilder sb = null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
name= (EditText)findViewById(R.id.name);
email = (EditText)findViewById(R.id.email);
tlf = (EditText)findViewById(R.id.tlf);
btn = (Button)findViewById(R.id.btn);
}
public void envoyerMessage (View v){
HttpClient client= new DefaultHttpClient();
HttpPost post=new HttpPost("http://xxxxcom/app.php");
String nam = name.getText().toString();
String mail = email.getText().toString();
String fon = tlf.getText().toString();
if(log.length() >0){
try {
List<NameValuePair> donnees = new ArrayList<NameValuePair>(1);
donnees.add(new BasicNameValuePair("id", nam ));
donnees.add(new BasicNameValuePair("mal", mail ));
donnees.add(new BasicNameValuePair("fn", fon ));
post.setEntity(new UrlEncodedFormEntity(donnees));
client.execute(post);
login.setText("");
Toast.makeText(this, "valid login", Toast.LENGTH_SHORT).show();
Thanks
My suggestion is use Volley, here is a very mini sample:
https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java
A Jar to Volley.
But you could try this Util:
public static class Connector extends AsyncTask<String, Object, Object> {
private static final int DEFAULT_CNN_TIME_OUT = 1000 * 20;
private static String USER_AGENT;
private String mUrl;
private byte[] mBody;
public Connector( Context _cxt ) {
super();
if( TextUtils.isEmpty( USER_AGENT ) ) {
// Without this, the default provided by API will be like "Dalvik/1.6.0 (Linux; U; Android 4.0.4; BASE_Lutea_3 Build/IMM76D)" .
USER_AGENT = new WebView( _cxt ).getSettings().getUserAgentString();
}
}
/*
* Convenient function to execute the connecting task.
*/
public void submit( String _url ) {
this.execute( _url );
}
#Override
protected Object doInBackground( String... _params ) {
mUrl = _params[0];
Object ret = null;
HttpURLConnection conn = null;
try {
synchronized( Connector.class ) {
InputStream in = null;
conn = connect( mUrl );
// if we don't do conn.setRequestProperty( "Accept-Encoding", "gzip" ), the wrapper GZIPInputStream can be removed.
onConnectorInputStream( in = new GZIPInputStream( conn.getInputStream() ) );
in.close();
in = null;
}
}
catch( Exception _e ) {
ret = _e;
}
finally {
if( conn != null ) {
conn.disconnect();
conn = null;
}
}
return ret;
}
#Override
protected void onPostExecute( Object _result ) {
if( _result instanceof SocketTimeoutException ) {
onConnectorConnectTimout();
} else if( _result instanceof ConnectorPostConnectException ) {
onConnectorError( ((ConnectorPostConnectException) _result).getStatus() );
} else if( _result instanceof Exception ) {
onConnectorInvalidConnect( (Exception) _result );
} else if( _result == null ) {
onConnectorFinished();
}
handleEstablishedConnection();
}
/*
* Internal help and test function.
*/
private static void handleEstablishedConnection() {
try {
Log.v( TAG, "Connection is established." );
CookieStore cs = CookieManager.getInstance().getCookieStore();
if( cs != null ) {
Log.v( TAG, "------------cookies------------" );
List<Cookie> list = cs.getCookies();
if( list != null && list.size() > 0 ) {
StringBuilder cookieBuilder = new StringBuilder();
for( Cookie c : list ) {
cookieBuilder
.append( c.getName().trim() )
.append( "=>" )
.append( c.getValue().trim() )
.append( "=>" )
.append( c.getDomain() );
Log.v( TAG, cookieBuilder.toString() );
cookieBuilder.delete( 0, cookieBuilder.length() - 1 );
}
cookieBuilder = null;
} else {
Log.v( TAG, "Empty cookies." );
}
cs = null;
list = null;
}
}
catch( Exception _e ) {
Log.e( TAG, "Error in handleEstablishedConnection: " + _e.getMessage() );
}
finally {
}
}
private HttpURLConnection connect( String _urlStr ) throws Exception {
URL url = null;
HttpURLConnection conn = null;
try {
try {
url = new URL( _urlStr );
}
catch( MalformedURLException e ) {
throw new IllegalArgumentException( "Invalid url: " + _urlStr );
}
conn = preConnect( url );
doConnect( conn );
conn = postConnect( conn );
}
catch( Exception _e ) {
throw _e;
}
finally {
url = null;
}
return conn;
}
private HttpURLConnection preConnect( URL url ) throws Exception {
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches( false );
// http://www.aswinanand.com/2009/01/httpurlconnectionsetfollowredirects-bug/comment-page-1/#comment-13330
// see the url to learn more about the problem of redirect
conn.setInstanceFollowRedirects( false );
conn.setDoOutput( true );// allows body
mBody = getBody();
if( hasBody() ) {
conn.setFixedLengthStreamingMode( mBody.length );
}
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Connection", "Keep-Alive" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded;charset=UTF-8" );
conn.setRequestProperty( "User-Agent", USER_AGENT );
conn.setRequestProperty( "Accept-Encoding", "gzip" );// force server to send in Content-Encoding: gzip .
String cookies = onCookie();
if( !TextUtils.isEmpty( cookies ) ) {
conn.setRequestProperty( "Cookie", onCookie() );
cookies = null;
}
conn.setConnectTimeout( onSetConnectTimeout() );
return conn;
}
/*
* Convenient function to check the exiting of body.
*/
private boolean hasBody() {
return mBody != null && mBody.length > 0;
}
private void doConnect( HttpURLConnection conn ) throws Exception {
OutputStream out; // the outgoing stream
out = conn.getOutputStream();
if( hasBody() ) {
out.write( mBody );
}
out.close();
out = null;
}
private HttpURLConnection postConnect( HttpURLConnection conn ) throws Exception {
int status = conn.getResponseCode();
if( status != HttpURLConnection.HTTP_OK ) {
throw new ConnectorPostConnectException( status );
} else {
CookieManager.getInstance().put( conn.getURL().toURI(), conn.getHeaderFields() );
return conn;
}
}
private byte[] getBody() {
byte[] body = null;
String bodyString = onSetBody();
if( !TextUtils.isEmpty( bodyString ) ) {
body = bodyString.getBytes();
}
return body;
}
// ------------------------------------------------
// Overrides methods here
// ------------------------------------------------
protected int onSetConnectTimeout() {
return DEFAULT_CNN_TIME_OUT;
}
protected String onCookie() {
return null;
}
protected String onSetBody() {
return null;
}
protected void onConnectorConnectTimout() {
Log.e( TAG, "Handling connector timeout gracefully." );
}
protected void onConnectorError( int _status ) {
Log.e( TAG, "Handling connector error(responsed) gracefully: " + _status );
}
protected void onConnectorInvalidConnect( Exception _e ) {
Log.e( TAG, "Handling connector invalid connect(crash) gracefully: " + _e.toString() );
}
/*
* Read data here. The function runs in thread. To hook on UI thread use onConnectorFinished()
*/
protected void onConnectorInputStream( InputStream _in ) {
}
/*
* Last handler for a success connection
*/
protected void onConnectorFinished() {
}
}
Use this util:
mConn = new Util.Connector( getApplicationContext() ) {
#Override
protected String onSetBody() {
String body = null;
try {
StringBuilder bodyBuilder = new StringBuilder();
bodyBuilder
.append( "id=" )//.append(...)
.append( '&' )
.append( "mal=" )//.append(...)
body = bodyBuilder.toString();
bodyBuilder = null;
}
catch( Exception _e ) {
Log.e( TAG, "Error in onCreateBody: " + _e.getMessage() );
}
finally {
}
return body;
}
#Override
protected int onSetConnectTimeout() {
return 10 * 1000;
}
#Override
protected void onConnectorInvalidConnect( Exception _e ) {
super.onConnectorInvalidConnect( _e );
onErr();
}
#Override
protected void onConnectorError( int _status ) {
super.onConnectorError( _status );
onErr();
}
protected void onConnectorConnectTimout() {
super.onConnectorConnectTimout();
onErr();
}
private void onErr() {
//mConn.submit( URL );
};
#Override
protected void onConnectorFinished() {
}
#Override
protected void onConnectorInputStream( InputStream _in ) {
}
};
mConn.submit( URL );
Related
I am trying get the dropdown list item from my database in my RecyclerView but whenever i try loading me recyclerView Activity the app crashes.
Code Form my RecyclerView Adapter :
public class Register_Adapter extends RecyclerView.Adapter<Register_Adapter.MyHolder> {
//Line number 40
private Context context;
List<dataRegComplaint> data = Collections.emptyList();
List<productlist> data1 = new ArrayList<>( );
Spinner product;
String total;
public static final int CONNECTION_TIMEOUT = 100000;
public static final int READ_TIMEOUT = 150000;
View v;
public Register_Adapter(complaintReg complaintReg,List<dataRegComplaint> data) {
this.context = complaintReg;
this.data = data;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.container_register, viewGroup, false);
return new MyHolder( v );
//Line number 60
}
#Override
public void onBindViewHolder(#NonNull MyHolder myHolder, int i) {
final dataRegComplaint current=data.get(i);
myHolder.client.setText(current.getClientName());
myHolder.location.setText("Location: " + current.getAddress());
myHolder.category.setText("Reason: " + current.getCategory());
myHolder.locationid = current.getlocationid();
myHolder.complaint_register.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
total = current.getlocationid();
Log.e( TAG,"Location id :"+total );
context.startActivity( new Intent( context, Register_New_Complaint.class ) );
}
} );
}
#Override
public int getItemCount() {
return data.size();
}
public class MyHolder extends RecyclerView.ViewHolder{
TextView client,location,category;
Button complaint_register;
String locationid;
public MyHolder(#NonNull View itemView) {
super( itemView );
client = (TextView) itemView.findViewById( R.id.textclient );
location = (TextView) itemView.findViewById( R.id.textlocation );
product = (Spinner) itemView.findViewById( R.id.textproduct1 );
category = (TextView) itemView.findViewById( R.id.textcategory );
complaint_register = (Button) itemView.findViewById( R.id.button_register );
product.setOnItemSelectedListener( (AdapterView.OnItemSelectedListener) context );
}
//Line number 105
}
private class GetProduct extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
HttpURLConnection conn;
URL url = null;
try {
url = new URL( "http://100.98.115.205:8089/productlist.php" );
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( READ_TIMEOUT );
conn.setConnectTimeout( CONNECTION_TIMEOUT );
conn.setRequestMethod( "POST" );
conn.setDoOutput( true );
OutputStream outputStream = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter( outputStream, "UTF-8" ) );
String post_data = URLEncoder.encode( "total", "UTF-8" ) + "=" + URLEncoder.encode(total, "UTF-8" );
Log.e( TAG, "POST DATAv :"+post_data );
bufferedWriter.write( post_data );
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader( new InputStreamReader( input ) );
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append( line );
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute( result );
Log.e( TAG, "RESULT :" +result );
try {
JSONArray jArray = new JSONArray( result );
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject( i );
productlist fishData = new productlist(
json_data.getString( "prod_name" ) );
data1.add( fishData );
Log.e( TAG, "DATA reesult :" +fishData );
}
populateSpinner();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for(int i = 0; i < data1.size(); i++){
lables.add( data1.get( i ).getSiteid());
Log.e( TAG, "Spinner :" +lables.add( data1.get( i ).getSiteid()) );
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>( context,android.R.layout.simple_spinner_dropdown_item, lables );
spinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
product.setAdapter( spinnerAdapter );
}
}
LogCat :
java.lang.ClassCastException: nikhil.loginapp.com.complaintReg cannot be cast to android.widget.AdapterView$OnItemSelectedListener
at nikhil.loginapp.com.Register_Adapter$MyHolder.<init>(Register_Adapter.java:105)
at nikhil.loginapp.com.Register_Adapter.onCreateViewHolder(Register_Adapter.java:60)
at nikhil.loginapp.com.Register_Adapter.onCreateViewHolder(Register_Adapter.java:40)
I am getting my data in my PostExecute function but after that its showing error in Spinner and app crashes.
Some one help me out.
im sorry but im new at android programming, so this may seem like a very stupid question.
i've established connection to my JSON data, but i need to only fetch the data i need, and not all unnecessary data. My Json looks like this:
data":[{"id":1,"temperature":"21.375","humidity":"28"}
Here i only need id: 1, temperature: 21.375 and humidity: 28
to establish connection i have following method:
private class jsonConnection extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
String username = "websiteUsername";
String password = "websitePassword";
String credentials = username + ":" + password;
String sensorID = "1";
String api = "api";
String websiteURL = "https://" + credentials + "#website.com" + "/" + sensorID + "/" + api;
String credBase64 = Base64.encodeToString( credentials.getBytes(), Base64.DEFAULT ).replace( "\n", "" );
try {
URL url = new URL( websiteURL );
System.out.println( url );
System.out.println( credentials );
System.out.println( websiteURL );
connection = (HttpsURLConnection) url.openConnection();
String basicAuth = "Basic " + new String( encodeBase64URLSafeString( credentials.getBytes() ) );
connection.setRequestProperty( "Authorization", basicAuth );
connection.setRequestMethod( "GET" );
connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
connection.setRequestProperty( "Content-Language", "en-US" );
connection.setUseCaches( false );
connection.setDoInput( true );
connection.setDoOutput( true );
connection.connect();
InputStream stream = connection.getInputStream();
bufferedReader = new BufferedReader( new InputStreamReader( stream ) );
//StringBuffer buffer = new StringBuffer();
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog( MainActivity.this );
pd.setMessage( "Please wait" );
pd.setCancelable( false );
pd.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute( result );
if (pd.isShowing()) {
pd.dismiss();
}
ScrollingMovementMethod());
System.out.println( data );
json_string = data;
System.out.println( "json_string: " + json_string );
}
}
i imagine i have to do something like this, but i'm not sure how to continue.
try {
JSONObject parentObject = new JSONObject( data );
JSONArray parentArray = parentObject.getJSONArray( "data" );
JSONObject finalObject = parentArray.getJSONObject( 0 );
int idName = finalObject.getInt( "id" );
int tempName = finalObject.getInt( "temperature" );
int humName = finalObject.getInt( "humidity" );
String batName = finalObject.getString( "battery" );
String modeName = finalObject.getString( "mode" );
String dateName = finalObject.getString( "date_time" );
String timeName = finalObject.getString( "date_time" );
String luxName = finalObject.getString( "lux" );
System.out.println( idName + tempName + humName + batName + modeName + dateName + timeName + luxName );
} catch (JSONException e) {
e.printStackTrace();
}
I have a suspicion that it should not be data inside the parameter, but perhaps something else, and maybe that would fix it?
JSONObject parentObject = new JSONObject( data );
I keep on getting a null pointer exception error. I looked through my code and I am not sure why I am getting this error. I populates when i complile the program
The error reads like this
Null pointer Exception: Attempt to invoke virtual method int java.lang.String.length() on a null object reference. Thanks in advance.
EditText enterCity;
TextView weatherView;
public void onClick (View view) {
downloadAPIInfo task = new downloadAPIInfo();
String APIKEY = "b4fabae83c89c469d7a458a230b7a267";
String website = "http://api.openweathermap.org/data/2.5/weather?q=";
String url = website + enterCity.getText().toString() + APIKEY;
task.execute(url);
Log.i("User Entry", enterCity.getText().toString());
}
public class downloadAPIInfo extends AsyncTask<String, Void, String> {
URL url;
HttpURLConnection httpURLConnection = null;
String result = "";
#Override
protected String doInBackground(String... urls) {
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream input = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int data = reader.read();
while(data != -1) {
char one = (char) data;
result += one;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Onpostexecute interacts with the UI
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject object = new JSONObject(result);
String weatherInfo = object.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray array = new JSONArray(weatherInfo);
for(int i = 0; i < array.length(); i++ ) {
JSONObject jsonPart = array.getJSONObject(i);
Log.i("main", jsonPart.getString("main"));
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if(main != "" && description != "") {
message+= main + ":" + description + "\r\n";
}
}
if(message != "") {
weatherView.setText(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Log.i("WebsiteContent", result);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enterCity = (EditText) findViewById(R.id.cityeditText);
weatherView = (TextView) findViewById(R.id.weathertextView);
}
}
The JSONArray named 'array' is null in your onPostExecute mehtod.
Most probably your weatherInfo string is null.
I suggest you post the full stacktrace for a better explanation.
I want to get an Number from a String.
My Code for this Class is:
The XML is download correct, it founds my Value String but i get not the number from the String.
public class XMLProcessor extends AsyncTask<String, Void, String> {
private String rssURL;
private PostParserDelegate delegate;
private ArrayList<Post> posts;
String euro;
private StringBuilder buffer;
TextView mxntoeur;
TextView eurtomxn;
public XMLProcessor(String rssURL, PostParserDelegate delegate) {
this.rssURL = rssURL;
this.delegate = delegate;
posts = new ArrayList<Post>();
}
#Override
protected String doInBackground(String... strings) {
buffer = new StringBuilder();
try {
URL url = new URL(rssURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// HTTP Status "OK" -> HTTPCODE 200
int httpResponse = httpURLConnection.getResponseCode();
if ( httpResponse != 200) {
throw new Exception("Fehlercode: " + httpResponse);
}
InputStream input = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int charactersRead;
char[] tmpChars = new char[400];
while (true) {
charactersRead = reader.read(tmpChars);
if (charactersRead <= 0) {
break;
}
buffer.append(String.copyValueOf(tmpChars, 0, charactersRead));
}
return buffer.toString();
} catch (Exception e) {
Log.e("XMLProcessor", e.getMessage());
Log.e("XMLProcessor", e.getStackTrace().toString());
}
return String.valueOf(0);
}
#Override
protected void onPostExecute(String aDouble) {
super.onPostExecute(aDouble);
parse();
}
protected void parse()
{
String rawXML = buffer.toString();
Post aPost = null;
boolean isProcessingItem = false;
String innerValue ="";
try {
XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
parser.setInput(new StringReader(rawXML));
int event = parser.getEventType();
while (event !=XmlPullParser.END_DOCUMENT)
{
String tag = parser.getName();
switch ( event) {
case XmlPullParser.START_TAG:
if (tag == "item" ) {
Log.d("XMLProcessor", "Neuer Post!");
isProcessingItem = true;
aPost = new Post();
}
break;
case XmlPullParser.TEXT:
innerValue = parser.getText();
break;
case XmlPullParser.END_TAG:
if (isProcessingItem){
if (tag == "item") {
posts.add(aPost);
isProcessingItem = false;
}
} else if ( tag == "description") {
aPost.setPesoInEuro(innerValue);
euro = new String(innerValue.substring(13,21));
//euro = innerValue.substring(13,21);
eurtomxn.setText(euro);
}
break;
}
event = parser.next();
}
delegate.xmlFeedParsed(posts);
} catch (Exception e) {
Log.e("XMLProcess", e.getStackTrace().toString());
}
}
}
In innerValue i get the Correct Sting what i need
/n 1.00 EUR = 21.90612 MXN<br/>\n 1.00 MXN = 0.04565 EUR<br/>\n
Converter--\n
<a href="http://eur.de.fxexchangerate.com/mxn-exchange-rates-history.html">Historische
</a>
\n.
But my problem is, that i need this Number 21.90612. I have try it with substring(13,21), but it was no working.
Have you a idea, how i can fix my problem?
Thank you
It's not very clear what exactly is the Problem, it would be useful if you show the Exception!
Have you checked if the String innerValue has a valid lenght?
if(innerValue.lenght() >= 21){euro = innerValue.substring(13,21);} else {/* Do something here!*/}
}
I want to build an app android using webview,
I want the webview app to automaticaly logging me in with the parameter that I send using http-post method.
I was reference to this :
Logging in via HttpPost to a website via an application
but still can't logged to my web and it always showing me login form, i was supposed to send post data to:
android.erfolgmedia.com/new_login/log.php?act=in
and send email & password via http post by webview android,
this is my code:
url = "http://android.erfolgmedia.com/new_login/log.php?act=in";
String login_tag = "login";
String email = "adi#erfolgmedia.com";
String pass = "adiadi";
try{
List<NameValuePair> params2 = new ArrayList<NameValuePair>();
params2.add(new BasicNameValuePair("tag", login_tag));
params2.add(new BasicNameValuePair("email", email));
params2.add(new BasicNameValuePair("password", pass));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params2, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
String data = new BasicResponseHandler().handleResponse(response);
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new HelloWebViewClient());
webView.loadDataWithBaseURL(httppost.getURI().toString(), data, "text/html", HTTP.UTF_8, null);
webView.getSettings().setJavaScriptEnabled(true);
String postData = "tag" + "=" + login_tag + "&" + "email" + "=" + email + "&" + "password" + "=" + pass;
webView.postUrl(url, EncodingUtils.getBytes(postData, "utf-8"));
}catch(Exception e){
e.printStackTrace();
}
//openBrowser();
}
Thank you for your time! I really appreciate you taking a look at my question.
I once made the class below. I don't know if it is up to date, so you might need to tweak it somewhat. You can call it using:
RestWrapperAsync wrapper = new RestWrapperAsync();
wrapper.SetUp("url");
wrapper.setFormBodyJson(jsonArray); //or setform..
wrapper.SetAuthentication("name", "password");
wrapper.SetResponseCallback(this);
wrapper.execute();
public class RestWrapperAsync extends AsyncTask<Void, Integer, Object> {
private WeakReference<ResponseCallback> mResponseCallback;
private WeakReference<ProgressCallback> mProgressCallback;
public interface ResponseCallback {
public void OnRequestSuccess(String response);
public void OnRequestError(Exception ex);
}
public interface ProgressCallback {
public void OnProgressUpdate(int progress);
}
public void SetResponseCallback(ResponseCallback callback){
mResponseCallback = new WeakReference<ResponseCallback>(callback);
}
public void setProgressCallback(ProgressCallback callback) {
mProgressCallback = new WeakReference<ProgressCallback>(callback);
}
private boolean getDetailsFromPost = false;
public void SetGetDetailsFromPost(boolean value){
getDetailsFromPost = value;
}
HttpURLConnection mConnection;
String mFormBody;
File mUploadFile;
String mUploadFileName;
JSONArray mFormBodyJSONArray;
JSONObject mFormBodyJSON;
/**
* Sets up the connection and the url
* #param siteUrl
*/
public void SetUp(String siteUrl, boolean doOutput){
try
{
URL url=null;
if (siteUrl!=null) {
url = new URL(siteUrl);
}
else {
url = new URL("https://xxxx");
}
mConnection = (HttpURLConnection) url.openConnection();
mConnection.setReadTimeout(10000 /* milliseconds */);
mConnection.setConnectTimeout(5000 /* milliseconds */);
mConnection.setRequestMethod("GET"); //set to get initially
if (doOutput){
//mConnection.setDoOutput(true);
mConnection.setDoInput(true);
}
else
mConnection.setDoInput(true);
}
catch (Exception ex){
Log.e("ERROR","Exception setting up connection:"+ex.getMessage());
}
}
/**
* Sets up form body for post requests
* #param formData
*/
public void setFormBody(List<NameValuePair> formData){
if (formData == null) {
mFormBody = "";
return;
}
try
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < formData.size(); i++) {
NameValuePair item = formData.get(i);
sb.append( URLEncoder.encode(item.getName(),"UTF-8") );
sb.append("=");
sb.append( URLEncoder.encode(item.getValue(),"UTF-8") );
if (i != (formData.size() - 1)) {
sb.append("&");
}
}
mFormBody = sb.toString();
}
catch(Exception ex){
Log.e("ERROR","Exception setting up connection:"+ex.getMessage());
}
}
/**
* Sets up form body for post request
* #param object
*/
public void setFormBodyJson(JSONArray object){
mFormBodyJSONArray = object;
}
/**
* Sets up form body for post request
* #param object
*/
public void setFormBodyJson(JSONObject object){
mFormBodyJSON = object;
}
/**
* Write out Json array to outputstream
* #param charset
* #param output
* #throws IOException
*/
private void writeFormDataJSON(JSONArray charset, OutputStream output) throws IOException {
try
{
output.write(charset.toString().getBytes());
output.flush();
}
finally
{
if (output != null) {
output.close();
}
}
}
/**
* Write out Json object to outputstream
* #param charset
* #param output
* #throws IOException
*/
private void writeFormDataJSON(JSONObject charset, OutputStream output) throws IOException {
try
{
output.write(charset.toString().getBytes());
output.flush();
}
finally
{
if (output != null) {
output.close();
}
}
}
/**
* Write out Charset to outputStream
* #param charset
* #param output
* #throws IOException
*/
private void writeFormData(String charset, OutputStream output) throws IOException {
try
{
output.write(mFormBody.getBytes(charset));
output.flush();
}
finally
{
if (output != null) {
output.close();
}
}
}
/**
* Sets up authentication
* #param username
* #param password
*/
public void SetAuthentication(String username, String password){
if (this.mConnection==null) {
Log.e("RestWrapper","Autentication called, but connection = null");
}
else
attachBasicAuthentication(mConnection,username,password);
}
/**
* Attaches authorization to header
* #param connection
* #param username
* #param password
*/
private static void attachBasicAuthentication(URLConnection connection, String username, String password) {
//Add Basic Authentication Headers
String userpassword = username + ":" + password;
String encodedAuthorization =
Base64.encodeToString(userpassword.getBytes(), Base64.NO_WRAP);
connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization);
}
public void setUploadFile(File file, String fileName) {
mUploadFile = file;
mUploadFileName = fileName;
}
/**
* Do network connection in background
*/
#Override
protected Object doInBackground(Void... arg0) {
return CallService(true);
}
/**
* The actual call to the web api's
* #param isAsyn
* #return
*/
public Object CallService(boolean isAsyn){
try
{
String charset = Charset.defaultCharset().displayName();
if (mFormBodyJSON != null) {
mConnection.setDoOutput(true);
mConnection.setRequestMethod("POST");
mConnection.setRequestProperty("Content-Type","application/json; charset="+charset);
mConnection.setFixedLengthStreamingMode(mFormBodyJSON.toString().length());
}
else if (mFormBodyJSONArray != null) {
mConnection.setDoOutput(true);
mConnection.setRequestMethod("POST");
mConnection.setRequestProperty("Content-Type","application/json; charset="+charset);
mConnection.setFixedLengthStreamingMode(mFormBodyJSONArray.toString().length());
}
else if (mFormBody != null) {
mConnection.setDoOutput(true);
mConnection.setRequestMethod("POST"); //change to post
mConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset="+charset);
mConnection.setFixedLengthStreamingMode(mFormBody.length());
}
if (isAsyn)
this.publishProgress(1);
mConnection.connect();
if (mFormBodyJSON!=null){
OutputStream out = mConnection.getOutputStream();
writeFormDataJSON(mFormBodyJSON, out);
}
else if (mFormBodyJSONArray!=null){
OutputStream out = mConnection.getOutputStream();
writeFormDataJSON(mFormBodyJSONArray, out);
}
else if (mFormBody != null) {
OutputStream out = mConnection.getOutputStream();
writeFormData(charset, out);
}
int status=0;
status = mConnection.getResponseCode();
if (isAsyn)
this.publishProgress(2);
if (status == 204){
if (!getDetailsFromPost){
return Constants.DATAPOSTEDCORRECTLY;
}
}
if (status >= 300){
String message = mConnection.getResponseMessage();
InputStream in = mConnection.getErrorStream();
String encoding = mConnection.getContentEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
if (in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding));
message = reader.readLine();
message = message.replace('"', ' ');
message = message.trim();
return new HttpResponseException(status, message);
}
}
//Get response data back
InputStream in = mConnection.getInputStream();
String encoding = mConnection.getContentEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
this.publishProgress(3);
BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding));
String result = reader.readLine();
return result;
}
catch (Exception ex){
return ex;
}
finally {
if (mConnection != null) {
mConnection.disconnect();
}
}
}
#Override
protected void onProgressUpdate(Integer... values) {
if (mProgressCallback != null && mProgressCallback.get() != null) {
mProgressCallback.get().OnProgressUpdate(values[0]);
}
}
#Override
protected void onPostExecute(Object result) {
if (mResponseCallback != null && mResponseCallback.get() != null) {
if (result instanceof String) {
mResponseCallback.get().OnRequestSuccess((String) result);
}
else if (result instanceof Exception) {
mResponseCallback.get().OnRequestError((Exception) result);
}
else {
mResponseCallback.get().OnRequestError(new IOException("Unknown Error Contacting Host"));
}
mResponseCallback = null;
mProgressCallback = null;
}
}
}