For some reason whenever I try to load a URL gotten from a GET request to a server it won't load but If i try to load the string directly it works. Here is my code:
new Thread(new Runnable() {
#Override public void run() {
try {
URL obj = new URL(url1 + overallid);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.addRequestProperty("User-Agent", "Mozilla/4.76");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString().replaceAll("\\s", ""));
System.out.println("Set pic to: " + pic);
Picasso.with(LoginActivity.this).load(pic).into(image);
i++;
overallid++;
} catch (Exception ex) {
System.out.println(ex);
}
}
}).start();
If I make pic = a imgur link straight up it works but if I grab it from the GET it doesn't work. Any ideas?
Thanks,
Quinn(Fusion)
Picasso should be called from the Main Thread... try out this code:
Handler mainThreadHandler=new Handler();
new Thread(new Runnable() {
#Override
public void run() {
try {
URL obj = new URL(url1 + overallid);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.addRequestProperty("User-Agent", "Mozilla/4.76");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString().replaceAll("\\s", ""));
System.out.println("Set pic to: " + pic);
mainThreadHandler.post(new Runnable() {
#Override
public void run() {
Picasso.with(LoginActivity.this).load(pic).into(image);
}
});
i++;
overallid++;
} catch (Exception ex) {
System.out.println(ex);
}
}
}).start();
Here is an example to handle the bitmap downloading.
BufferedInputStream inputStream = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
URL url = new URL("the image url to load");
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
inputStream = new BufferedInputStream(connection.getInputStream());
byte[] buffer = new byte[8192];
int n = -1;
while ((n = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, n);
}
final Bitmap bitmap = BitmapFactory.decodeByteArray(
outputStream.toByteArray(), 0, outputStream.size());
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO handle image here
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Related
Does it possible, to get from client and
objetObjectInputStream
and
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
for example, some client send me tet message, and someone send files. Should I make a new socket server for each?
public class ServerRequests {
Connection con = new Connection();
private Socket socket;
private BufferedReader in;
private BufferedWriter out;
public ServerRequests(Socket socket) throws IOException {
this.socket = socket;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
run();
}
public void run() {
String word;
try {
String object;
ObjectInputStream obIn = new ObjectInputStream(socket.getInputStream());
while ((object = (String) obIn.readObject()) != null){
if (object.contains("F47S")){
String[] result = object.split(":");
String fileName = result[1];
String url = result[2];
String culture = result[3];
System.out.println("FileName:" +fileName);
System.out.println("url:" +url);
FileOutputStream outOb = null;
if(culture.contains("test")) {
outOb = new FileOutputStream(fileName);
}
DataInputStream inOb = new DataInputStream(socket.getInputStream());
byte[] bytes = new byte[5*1024];
int count, total=0;
long lenght = inOb.readLong();
while ((count = inOb.read(bytes)) > -1) {
total+=count;
outOb.write(bytes, 0, count);
if (total==lenght) break;
}
outOb.close();
}
}
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// while (true) {
word = in.readLine();
System.out.println(word);
if (word != null) {
String[] result = word.split(":");
String type = result[0];
if (type.contains("AUTH")) {
String login = result[2];
String pass = result[4];
String gui = con.checkLogin(pass, login);
auth(gui);
}
} catch (IOException e) {
}
}
private void auth(String gui) {
try {
out.write(gui + "\n");
out.flush();
} catch (IOException ignored) {
}
}
private void success(String status) {
try {
out.write(status+ "\n");
out.flush();
} catch (IOException ignored) {
}
}
}
I created a class Students, that invokes a thread which needs to fill a linked list with students.
class Students{
private LinkedList<Student> students = new LinkedList<Student>();
android.os.Handler handler = new android.os.Handler();
public String Fill() throws MalformedURLException {
String msg = "++";
new Thread(){
public void run(){
HttpURLConnection htcon=null;
try {
URL my_url = new URL("http://www.whatever.net/fill.php");
htcon = (HttpURLConnection) my_url.openConnection();
htcon.setDoOutput(true);
htcon.setUseCaches(false);
htcon.connect();
int responseCode = htcon.getResponseCode();
if(responseCode ==HttpURLConnection.HTTP_OK){
InputStream stream = htcon.getInputStream();
BufferedReader bfr = new BufferedReader(new InputStreamReader(stream,"UTF-8"));
String line = "";
StringBuilder strbld = new StringBuilder();
while ((line = bfr.readLine()) != null) {
strbld.append(line);
}
if (bfr!=null)
{
bfr.close();
}
String[] ary = strbld.toString().split("\n");
for (int i = 0; i < ary.length; i++) {
final Student temp = new Student(ary[i].toString().split(":")[0], "1210",Integer.parseInt(ary[i].toString().split(":")[1]), 0);
handler.post(new Runnable() {
#Override
public void run() {
students.push(new Student("jjj","k",9,9));
}
});
}//for
if (htcon!=null)
htcon.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
}.start();
return toBinaryString(students.size());
}
problem is, when handler runs, it doesn't change the list. size is still 0
here is how my UI class looks like(main activity)
TextView txtv = (TextView) findViewById(R.id.textv);
Students students1 = new Students();
try {
msg = students1.Fill();
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
}
Your thread is running asynchronously. So, it will immediately execute:
return toBinaryString(students.size());
while the thread is still on the progress. AsyncTask is really enough for your problem. Hope it helps.
I am collecting data from Android App(Accelerometer and Gyro) and send it to Desktop app via Java Socket but in high rates
(SENSOR_DELAY_FASTEST,SENSOR_DELAY_GAME)
Notes :
readingsList : contains all reading from sensors
I remove from list the data being sent to server
Only data sent once and i made sure it's ordered from client side
but i got them unordered in server side ( I received all data but not ordered)
processData(String reading) function may takes time but not too much
Client Code :
class SocketClientThread implements Runnable {
public SocketClientThread(){
}
public void run() {
while (!Thread.currentThread().isInterrupted() && breathingStarted) {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
socket.setSendBufferSize(Integer.MAX_VALUE);
socket.setReceiveBufferSize(Integer.MAX_VALUE);
int lastCount = readingsList.size();
out.println(readingsList);
out.flush();
out.close();
int toberemoved = lastCount;
if(readingsList.size() > 0){
for (int i = 0; i < toberemoved; i++) {
readingsList.remove(0);
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
Server Code :
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(minutes*60*1000);
Thread thread = new Thread() {
public void run() {
while(!isStopped)
{
try
{
Socket connection = serverSocket.accept();
connection.setReceiveBufferSize(Integer.MAX_VALUE);
connection.setSendBufferSize(Integer.MAX_VALUE);
BufferedReader input =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
PrintWriter out =
new PrintWriter(connection.getOutputStream(), true);
String inputLine;
while ((inputLine = input.readLine()) != null) {
recentReading = inputLine;
String oldReading = recentReading;
String modifiedReading = oldReading.replace("[", "");
modifiedReading = modifiedReading.replace("]", "");
String [] readings = modifiedReading.split(",");
for (int i = 0; i < readings.length; i++) {
String currentReading = readings[i].trim();
String [] tokens = currentReading.split("_");
processData(currentReading);
}
}
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
display.syncExec(new Runnable() {
public void run() {
statusVal.setText("Socket timed out!");
}
});
break;
}catch(SocketException s)
{
if(serverSocket.isClosed()){
display.syncExec(new Runnable() {
public void run() {
statusVal.setText("Disconnected");
}
});
}
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
};
thread.setDaemon(true);
thread.start();
I am getting data after it's time (not ordered)
I need help with getting information from spotify. How from this link : https://api.spotify.com/v1/search?q=Songs+of+Innocence&type=album
Can I take url:
"height" : 64,
"url" : "https://i.scdn.co/image/eb740cef5aa3d5e119baf868bdff2dbb5cc1a59b",
"width" : 64
And assign url to variable s in my code below:
public void getCover(String album) {
String query = "https://api.spotify.com/v1/search?q="+ encodeField(album)+"=album";
java.net.URL url = null;
try {
BufferedImage image = null;
url = new java.net.URL(query);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
e.printStackTrace();
}
// get the text from the stream as lines
java.io.BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String s;
try {
s = reader.readLine()) // read link with image 64x64 resolution
} catch (IOException e) {
e.printStackTrace();
}
try {
//URL url2 = new URL("https://i.scdn.co/image/eb740cef5aa3d5e119baf868bdff2dbb5cc1a59b");
URL url2 = new URL(s);
image = ImageIO.read(url2);
ImageIcon icon = new ImageIcon(image);
jLabel2.setIcon(icon);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String filePath = "C:/Program Files/ZBar/bin/zbarimg -d C:/Program Files/ZBar/examples/barcode.png";
try {
System.out.println("hello");
Process p = Runtime.getRuntime().exec(filePath);
//BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println("World");
final InputStream stdout = p.getInputStream();
final OutputStream stdin = p.getOutputStream();
new Thread(new Runnable() {
#Override
public void run() {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
try {
while ((line = br.readLine()) != null) {
System.out.println("[OUT] " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = System.in.read(buffer)) != -1) {
for(int i = 0; i < buffer.length; i++) {
int intValue = new Byte(buffer[i]).intValue();
if (intValue == 0) {
bytesRead = i;
break;
}
}
// for some reason there are 2 extra bytes on the end
stdin.write(buffer, 0, bytesRead-2);
System.out.println("[IN] " + new String(buffer, 0, bytesRead-2) + " [/IN]");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You probably shouldn't be invoking an external process to decode like that, I suspect you're receiving a '\r\n' (aka Carraige Return Line Feed) from your external process. I recommend you use a Java library to perform the decode... here is how you might with ZXing "Zebra Crossing".