演習の解答例

演習1

import processing.net.*;

size(400, 400);

Client client = new Client(this, "virgo.is.chs.nihon-u.ac.jp", 80);
client.write("GET /~onoue/20181026.html HTTP/1.0\r\n");
client.write("\r\n");

while (client.active()) {
  if (client.available() > 0) {
    String line = client.readStringUntil('\n');
    print(line);
    if (line != null && line.length() == 2) {
      break;
    }
  }
}

int bufferIndex = 0;
byte[] buffer = new byte[1000000];
byte[] tmp = new byte[1000000];
while (client.active()) {
  if (client.available() > 0) {
    int n = client.readBytes(tmp);
    for (int i = 0; i < n; ++i) {
      buffer[bufferIndex++] = tmp[i];
    }
  }
}
String body = new String(buffer, 0, bufferIndex);
println(body);

演習2

import processing.net.*;

size(600, 600);

Client client = new Client(this, "shibe.online", 80);
client.write("GET /api/shibes?count=10&urls=false&httpsUrls=false HTTP/1.1\r\n");
client.write("Host: shibe.online\r\n");
client.write("\r\n");

while (client.active()) {
  if (client.available() > 0) {
    String line = client.readStringUntil('\n');
    print(line);
    if (line != null && line.length() == 2) {
      break;
    }
  }
}

int bufferIndex = 0;
byte[] buffer = new byte[1000000];
while (client.active()) {
  String line = client.readStringUntil('\n');
  int size = unhex(trim(line));
  if (size == 0) {
    break;
  }
  for (int i = 0; i < size; ++i) {
    buffer[bufferIndex++] = (byte)client.read();
  }
  client.readStringUntil('\n');
}
String body = new String(buffer, 0, bufferIndex);

JSONArray json = parseJSONArray(body);
for (int i = 0; i < json.size(); ++i) {
  String path = json.getString(i);
  println(path);

  Client imageClient = new Client(this, "cdn.shibe.online", 80);
  imageClient.write("GET /shibes/" + path + ".jpg HTTP/1.0\r\n");
  imageClient.write("Host: cdn.shibe.online\r\n");
  imageClient.write("\r\n");

  while (imageClient.active()) {
    if (imageClient.available() > 0) {
      String line = imageClient.readStringUntil('\n');
      if (line != null && line.length() == 2) {
        break;
      }
    }
  }

  int imageBufferIndex = 0;
  byte[] imageBuffer = new byte[1000000];
  byte[] tmp = new byte[1000000];
  while (imageClient.active()) {
    if (imageClient.available() > 0) {
      int n = imageClient.readBytes(tmp);
      for (int j = 0; j < n; ++j) {
        imageBuffer[imageBufferIndex++] = tmp[j];
      }
    }
  }
  String filename = "tmp" + i + ".jpg";
  saveBytes(filename, imageBuffer);
  PImage img = loadImage(filename);
  image(img, width * (i % 3) / 3, height * (i / 3) / 3, width / 3, height / 3);
}

results matching ""

    No results matching ""