I am trying to send data to server when user mobile internet become active, in my application whenever internet connection is active my broadcast receiver call a service method.
Below is the method. I trying for both post and get method but it does not request to the site. I am not able to print "i am in service5"(Below i have printed).It does not update my database.
public class LocalService extends Service
{
....
....
public void sendfeedback(){
System.out.println("i am in service4");
String filename =MainScreenActivity.UserName;
HttpURLConnection urlConnection = null;
final String target_uri =
"http://readoline.com/feedback.php";
try {
BufferedReader mReader = new BufferedReader(new InputStreamReader(getApplicationContext().openFileInput(filename)));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = mReader.readLine()) != null) {
buffer.append(line + "\n");
}
System.out.println(buffer.toString());
try {
System.out.println("i am in service41"+buffer.toString());
Uri buildUri = Uri.parse("http://readoline.com/feedback.php" + "?").buildUpon()
.appendQueryParameter("user_id", filename)
.appendQueryParameter("feedback", buffer.toString())
.build();
URL url = new URL(buildUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
System.out.println("i am in service44");
/* PrintWriter out=new PrintWriter(urlConnection.getOutputStream());
out.write("user_id="+filename);
out.write("&");
out.write("feedback="+buffer.toString());
*/
System.out.println("i am in service5");
// Log.e(LOG_TAG,dataToSend.toString());
//out.close();
// Read the input stream into a String
}catch (IOException e){
System.out.println("i am in service6");
e.printStackTrace();
}finally {
if (urlConnection!=null){
urlConnection.disconnect();
}
}
}catch(Exception e){
}
}
}
Related
I am a beginner in the android studio. I will successfully connect the database but I don't know how to read a data 5 seconds once in an android studio.
I want to how to read data from the database every 5 seconds once
#Override
protected String doInBackground(String... voids) {
String result = "";
String name = voids[0];
String word = voids[1];
Log.d("myTag", "This is my test");
String connstr ="http://192.168.43.123/suruthi/login.php";
try {
URL url = new URL(connstr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream ops = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ops, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8")+"="+URLEncoder.encode(name, "UTF-8")
+"&&"+ URLEncoder.encode("pass", "UTF-8")+"="+URLEncoder.encode(word, "UTF-8");
writer.write(data);
writer.flush();
writer.close();
ops.close();
InputStream ips = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ips, "ISO-8859-1"));
String line ="";
while ((line = reader.readLine()) != null)
{
result += line;
}
reader.close();
ips.close();
http.disconnect();
return result;
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
}
}
The below timer function is working only image changes but it is not suitable for reading a database ever 5 sec once
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
#Override
public void run()
{
/* iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length)
{
i=0;
}*/
doInBackground();
}
});}}
catch (InterruptedException e)
{
}}};
}
I tried above the timer function to read a database but it is not working..please guide me to resolve the issues..
I want to develop a HTTP Proxy ,
The code is here ;
When I run my code , I get this exception :
Started on: 9999
request for : /setwindowsagentaddr
Encountered exception: java.net.MalformedURLException: no protocol: /setwindowsagentaddr
package proxy;
import java.net.*;
import java.io.*;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listenning = true;
// String host="192.168.1.10";
int port = 9999;
try{
port = Integer.parseInt(args[0]);
}catch(Exception e){
}
try{
serverSocket = new ServerSocket(port);
System.out.println("Started on: " + port);
}catch(Exception e){
// System.err.println("Could not listen on port: " + args[0]);
System.exit(0);
}
while(listenning){
new ProxyThread(serverSocket.accept()).start();
}
serverSocket.close();
}
}
and the ProxyThread here :
public class ProxyThread extends Thread {
private Socket socket = null;
private static final int BUFFER_SIZE = 32768;
public ProxyThread(Socket socket){
super("Proxy Thread");
this.socket=socket;
}
public void run(){
try {
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine , outputLine;
int cnt = 0 ;
String urlToCall="";
//get request from client
// socket.getPort();
while((inputLine=in.readLine()) != null){
try{
StringTokenizer tok = new StringTokenizer(inputLine);
tok.nextToken();
}catch(Exception e){
break;
}
///parse the first line of the request to get url
if(cnt==0){
String [] tokens = inputLine.split(" ");
urlToCall = tokens[1];
System.out.println("request for : "+ urlToCall);
}
cnt++;
}
BufferedReader rd = null;
try{
//System.out.println("sending request
//to real server for url: "
// + urlToCall);
///////////////////////////////////
//begin send request to server, get response from server
URL url = new URL(urlToCall);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
//not doing http post
conn.setDoOutput(false);
System.out.println("Type is : "+ conn.getContentType());
System.out.println("length is : "+ conn.getContentLength());
System.out.println("allow user interaction :"+ conn.getAllowUserInteraction());
System.out.println("content encoding : "+ conn.getContentEncoding());
System.out.println("type is : "+conn.getContentType());
// Get the response
InputStream is = null;
HttpURLConnection huc = (HttpURLConnection) conn;
if (conn.getContentLength() > 0) {
try {
is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
} catch (IOException ioe) {
System.out.println(
"********* IO EXCEPTION **********: " + ioe);
}
}
//end send request to server, get response from server
//begin send response to client
byte [] by = new byte[BUFFER_SIZE];
int index = is.read(by,0,BUFFER_SIZE);
while ( index != -1 )
{
out.write( by, 0, index );
index = is.read( by, 0, BUFFER_SIZE );
}
out.flush();
//end send response to client
}catch(Exception e){
//can redirect this to error log
System.err.println("Encountered exception: " + e);
//encountered error - just send nothing back, so
//processing can continue
out.writeBytes("");
}
//close out all resources
if (rd != null) {
rd.close();
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (socket != null) {
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
How can I fix this exceptions?
So the error isn't lying, /setwindowsagentaddr isn't a valid url. How would it know what protocol to use?
Try using something like http://localhost:8080/setwindowsagentaddr
This is the class containing the main() method:
public class MultithreadedProxyServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
int port = 10000; //default
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
//ignore me
System.out.println("gnore");
}
try {
serverSocket = new ServerSocket(port);
System.out.println("Started on: " + port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + args[0]);
System.exit(-1);
}
while (listening) {
new ProxyThread(serverSocket.accept()).start();
}
serverSocket.close();
}
}
And this is the ProxyThread class:
public class ProxyThread extends Thread {
private Socket socket = null;
private static final int BUFFER_SIZE = 32768;
public ProxyThread(Socket socket) {
super("ProxyThread");
this.socket = socket; //initialzed my parent before you initalize me
}
public void run() {
//get input from user
//send request to server
//get response from server
//send response to user
System.out.println("run");
try {
DataOutputStream out =
new DataOutputStream(socket.getOutputStream());
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String inputLine, outputLine;
int cnt = 0;
String urlToCall = "";
///////////////////////////////////
//begin get request from client
while ((inputLine = in.readLine()) != null) {
try {
StringTokenizer tok = new StringTokenizer(inputLine);
tok.nextToken();
} catch (Exception e) {
System.out.println("break");
break;
}
//parse the first line of the request to find the url
if (cnt == 0) {
String[] tokens = inputLine.split(" ");
urlToCall = tokens[1];
//can redirect this to output log
System.out.println("Request for : " + urlToCall);
}
cnt++;
}
//end get request from client
///////////////////////////////////
BufferedReader rd = null;
try {
//System.out.println("sending request
//to real server for url: "
// + urlToCall);
///////////////////////////////////
//begin send request to server, get response from server
URL url = new URL(urlToCall);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
//not doing HTTP posts
conn.setDoOutput(false);
//System.out.println("Type is: "
//+ conn.getContentType());
//System.out.println("content length: "
//+ conn.getContentLength());
//System.out.println("allowed user interaction: "
//+ conn.getAllowUserInteraction());
//System.out.println("content encoding: "
//+ conn.getContentEncoding());
//System.out.println("content type: "
//+ conn.getContentType());
// Get the response
InputStream is = null;
HttpURLConnection huc = (HttpURLConnection)conn;
if (conn.getContentLength() > 0) {
is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
}
//end send request to server, get response from server
///////////////////////////////////
///////////////////////////////////
//begin send response to client
byte by[] = new byte[ BUFFER_SIZE ];
int index = is.read( by, 0, BUFFER_SIZE );
while ( index != -1 )
{
out.write( by, 0, index );
index = is.read( by, 0, BUFFER_SIZE );
}
out.flush();
//end send response to client
///////////////////////////////////
} catch (Exception e) {
//can redirect this to error log
System.err.println("Encountered exception: " + e);
//encountered error - just send nothing back, so
//processing can continue
out.writeBytes("");
}
//close out all resources
if (rd != null) {
rd.close();
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have copy-pasted the above code from the internet, however I am having difficulties running it.
To answer the question from the post title, the run() method from ProxyThread class is called by JVM, after the thread has been started new ProxyThread(serverSocket.accept()).start(); and it usually contains the actual work that a thread should performed (in this case, it handles whatever the server socket receives and it accepts a connection from a client).
The moment when JVM calls run() method cannot be controlled by the programmer, but is after the thread has been started.
run() method is never called explicitly by the programmer.
I've created a small scraping class and the method below reads in the text from a page.
However, I've found that the method fails to close the connection properly. This results in a ton of open connections which cause my hosting company to then suspend my account. Is the below correct?
private String getPageText(String urlString) {
String pageText = "";
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder builder = new StringBuilder();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
builder.append(chars, 0, read);
pageText = builder.toString();
} catch (MalformedURLException e) {
Log.e(CLASS_NAME, "getPageText.MalformedUrlException", e);
} catch (IOException e) {
Log.e(CLASS_NAME, "getPageText.IOException", e);
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
Log.e(CLASS_NAME, "getPageText.IOException", e);
}
}
return pageText;
}
Your code is fine in the success case but will potentially leak connections in the failure cases (when the http server returns a 4xx or 5xx status code). In these cases HttpURLConnection provides the response body via .getErrorStream() rather than .getInputStream() and you should make sure to drain and close that stream as well.
URLConnection conn = null;
BufferedReader reader = null;
try {
conn = url.openConnection();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// ...
} finally {
if(reader != null) {
// ...
}
if(conn instanceof HttpURLConnection) {
InputStream err = ((HttpURLConnection)conn).getErrorStream();
if(err != null) {
byte[] buf = new byte[2048];
while(err.read(buf) >= 0) {}
err.close();
}
}
}
There probably needs to be another layer of try/catch inside that finally but you get the idea. You should not explicitly .disconnect() the connection unless you're sure there won't be any more requests for urls on that host in the near future - disconnect() will prevent subsequent requests from being pipelined over the existing connection, which for https in particular will slow things down considerably.
You are just closing the stream and not the connection, use the following structure:
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection)
u.openConnection();
conn.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
and then:
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
Log.e(CLASS_NAME, "getPageText.IOException", e);
}
}
try {
if (conn != null) {
conn.disconnect();
}
} catch (Exception ex) {}
}
I can pull the user's statuses with no problem with cURL, but when I connect with Java, the xml comes out truncated and my parser wants to cry. I'm testing with small users so it's not choke data or anything.
public void getRuserHx(){
System.out.println("Getting user status history...");
String https_url = "https://twitter.com/statuses/user_timeline/" + idS.rootUser + ".xml?count=100&page=[1-32]";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(15*1000);
//dump all the content into an xml file
print_content(con);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished downloading user status history.");
}
private void print_content(HttpsURLConnection con){
if(con!=null){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
File userHx = new File("/" + idS.rootUser + "Hx.xml");
PrintWriter out = new PrintWriter(idS.hoopoeData + userHx);
String input;
while ((input = br.readLine()) != null){
out.println(input);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
This request doesn't need auth. Sorry about my ugly code. My professor says input doesn't matter so my I/O is a trainwreck.
You have to flush the output stream when you write the content out. Did you flush or close the output stream?