What to do on android HttpURlConnection - java

As you can see from my code, I'm trying to programmatically log into a website using post/get...
I'm using the following code in Java, and it's working awesome.
But when I run this same code on android, the app doesn't work.
If I'm doing some encode its run but with wrong parameters!
So what do I have to do ?
final String httpParams=String.format("__LASTFOCUS=&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTEzOTM5NTcxNjQPZBYCZg9kFgICAQ8WAh4DZGlyBQNsdHIWAgIDDxYCHwAFA2x0chYKAgEPZBYGZg9kFgJmDw8WCB4EVGV4dAUCRU4eCENzc0NsYXNzBR5idG5MYW5ndWFnZSBidG5MYW5ndWFnZUN1cnJlbnQeCFRhYkluZGV4AQUAHgRfIVNCAgJkZAIBD2QWAmYPDxYEHwEFAkhFHwMBBQBkZAICD2QWAmYPDxYEHwEFAkVTHwMBBQBkZAIDDw8WAh8BBRdXYXNoaW5nIG1hY2hpbmVzIHN5c3RlbWRkAgcPZBYCAgEPFgIeBWNsYXNzBQxTaWduT3V0VGFiRU5kAgkPFgQfAAUDbHRyHwUFEFNpZ25PdXRTdWJNZW51RU4WAgIBDxYCHwUFEVNpZ25PdXRTdWJNZW51MUVOZAILD2QWAgIBDxYCHwAFA2x0chYCAgEPZBYCAgEPFgIfAAUDbHRyFgICAQ8WAh8ABQNsdHIWBAIBDxYCHwAFA2x0chYCAgEPDxYCHwEFFUxvZyBpbiB0byB5b3VyIHBvcnRhbGRkAgMPFgIfAAUDbHRyFghmD2QWAmYPZBYCZg8PFgIfAQUJVXNlciBuYW1lZGQCAQ9kFgJmD2QWAmYPDxYCHwEFCFBhc3N3b3JkZGQCAg9kFgICAQ9kFgQCAQ9kFgICAQ8QDxYCHwEFEUtlZXAgbWUgbG9nZ2VkIGluZGRkZAIDDxYCHwUFCmZsb2F0UmlnaHQWAgIBDw8WAh8BBRVGb3Jnb3QgeW91ciBwYXNzd29yZD9kZAIDD2QWAgIBD2QWAgIBDw8WAh8BBQVMb2dpbhYCHwUFDWxvZ2luYnV0dG9uRU5kGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBSdjdGwwMCRDb250ZW50UGxhY2VIb2xkZXIxJGNoa1JlbWVtYmVyTWXSsyj0x2ZHqL6cM7d%2FEoMVGnzRVw%3D%3D&__EVENTVALIDATION=%2FwEWDQKVkZe1BALj4YiXBgLltMbPAwKI0bD9DwKQxtj8BgL5%2B6qZBALP14C2DAL6qc7jBwLN49KjCQLo0YK0CQLS%2BavhCwKh5%2FXjDQLizN68CiDA9ZDgCfU8Py%2Bfp0mFjtZo08Sp&ctl00%24ContentPlaceHolder1%24UserName=%s&ctl00%24ContentPlaceHolder1%24Password=%s&ctl00%24ContentPlaceHolder1%24LoginButton=Login&ctl00%24hdnCurClientTimeZone=%2B02%3A00",userId,password);
try {
wr = new DataOutputStream($.getOutputStream());
wr.writeBytes(httpParams);
wr.flush();
} catch (IOException e) {
e.printStackTrace();
}

Related

DELETE Request in Android doesn't connect to server

So my question is how can I create a DELETE Request to an URL in Android Studio Java. I already have an Async Task which GET json from URL. So my question now is how can I create a DELETE request
EDIT:
So right now I got this code:
int pos = arrlist.get(info.position).getId();
URL_DELETE = "http://testserver/test/tesst.php?id=" + pos + "&username=" + username + "&password=" + password;
URL url = null;
try {
url = new URL(URL_DELETE);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
To understand the content of the given URL should be deleted. But if I run the code nothing happens.
You need to call connect() on the HttpURLConnection. Right now you're not actually making a connection to the server.
Based on your comments on the other answer, you're also trying to run this code on the main (UI) thread - you'll need to change your code to run on a background thread.
If you're using OkHttp:
Request request = new Request.Builder().delete().url(url).build();
Response rawResponse = null;
try {
rawResponse = new OkHttpClient().newCall(request).execute();
} catch (IOException e) {
System.err.println(e.getMessage());
}
String responseAsString = rawResponse.body().string();

Passing objects from server to android

I have a Java servlet web server and an android application that communicate with each other. What is the proper way of passing a custom object (EX: User object) from server to android.
Example:
User logs in through android device, the users email and password are sent to the server for authentication. Server now needs to send back to the android device the User object.
If you can attach an example or link to tutorial that would be great.
https://www.youtube.com/watch?v=Gyaay7OTy-w
make a class that extends AsyncTask
implement override methods (Alt+Insert)
In do in background:
Make an http url connection
try {
URL url=new URL(urladdress);
HttpURLConnection con= (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestMethod("POST")
con.setDoOutput(true);
con.setDoInput(true);
return con;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
now download the data from this connection
if(con==null) {
Toast.makeText(ctx,"Connection is null",Toast.LENGTH_LONG).show();
}
try{
InputStream is = new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer jsonData= new StringBuffer();
while ((line=br.readLine())!=null)
{
jsonData.append(line+"/n");
}
br.close();
is.close();
return jsonData.toString();
} catch (IOException e) {
e.printStackTrace();
}
now parse this jsonData
try{
JSONArray ja = new JSONArray(jsonData);
JSONObject jo = null;
//parse Data
}
In onPostExecute call the required java file which will receive data
write a script that convert data recived from your server and send data in json format
Note- these code belongs three different classes so don't try copy/paste
Use Retrofit, is quite simple and straightforward.
Retrofit has given almost all the API's to make server call and to receive response. Internally they also use GSON to do the parsing. you can go through the official website you will get more info and a tutorial.
Hope it helps

can not identify the cause of error to connect xampp (openfire) server by java

I am new in xmpp. For a whole day i and my project member stuck in connecting xmpp server(openfire version 3.9.3) by java. I am using smack(version 4.0.7) library. Here is simple code...
ConnectionConfiguration config =new ConnectionConfiguration("servername",5223);
XMPPTCPConnection connection = new XMPPTCPConnection(config);
// Connect to the server
try {
connection.connect();
connection.login("username", "password");
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
}
But when i run this code this errors is showing ...`
org.jivesoftware.smack.SmackException$NoResponseException
at org.jivesoftware.smack.XMPPConnection.throwConnectionExceptionOrNoResponse(XMPPConnection.java:548)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.throwConnectionExceptionOrNoResponse(XMPPTCPConnection.java:867)
at org.jivesoftware.smack.tcp.PacketReader.startup(PacketReader.java:113)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.initConnection(XMPPTCPConnection.java:482)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectUsingConfiguration(XMPPTCPConnection.java:440)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectInternal(XMPPTCPConnection.java:811)
at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:396)
at test.third.<init>(third.java:19)
at test.third.main(third.java:34)
There may be a silly mistake and easy solution, i googled but but somehow i am not getting the right solution.please help me. Thanks in advance

Why do I get FileNotFoundException when I create and try to write to file on Android emulator?

First off, I am not trying to write to the SDCard. I want to write some information to a file that persists between uses of the app. It is essentially a file to hold favorites of the particular user. Here is what the code looks like:
try {
File file = new File("favorites.txt");
if (file.exists()) {
Log.d(TAG, "File does exist.");
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
}
else {
Log.d(TAG, "File does not exist.");
return favDests;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
When running this code, we always get the "File does not exist." message in our DDMS log.
We have also tried the following code to no avail:
try {
File file = new File(GoLincoln.FAV_DEST_FILE);
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
It is this second portion of code that results in the FileNotFoundException.
I have read multiple tutorials on writing and reading files on Android and I believe I am following them pretty closely, so I am not sure why this code doesn't work successfully. I appreciate any help!
You shouldn't use the File class directly. Use Activity.getCacheDir() to get the cache dir which is specific to your application. Then use new File(cachedir, "filename.tmp") to create the file.
Preferences and SQLLite will both allow you to have persistent data without managing your own files.
To use shared preferences you grab it from your context, then you edit the values like so
mySharedPreferences = context.getSharedPreferences("DatabaseNameWhateverYouWant", 0);
mySharedPreferences.getEditor().putString("MyPreferenceName", "Value").commit();
To get a preference out
mySharedPreferences.getString("MyPreferenceName", "DefaultValue");
This is really the simplest way to do basic preferences, much easier then doing a file. More then strings are supported, most basic data types are available to be added to the Preferences class.

can I check if a file exists at a URL?

can I check if a file exists at a URL?
This link is very good for C#, what about java. I serach but i did not find good solution.
It's quite similar in Java. You just need to evaluate the HTTP Response code:
final URL url = new URL("http://some.where/file.html");
url.openConnection().getResponseCode();
A more complete example can be found here.
Contributing a clean version that's easier to copy and paste.
try {
final URL url = new URL("http://your/url");
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
int responseCode = huc.getResponseCode();
// Handle response code here...
} catch (UnknownHostException uhe) {
// Handle exceptions as necessary
} catch (FileNotFoundException fnfe) {
// Handle exceptions as necessary
} catch (Exception e) {
// Handle exceptions as necessary
}

Categories