Skip to content

Instantly share code, notes, and snippets.

@LanderlYoung

LanderlYoung/javaCode.java

Last active Oct 23, 2020
Embed
What would you like to do?
Life without jenny
String httpGet(String url) throws IOException {
URL u = new URL(url);
URLConnection conn = u.openConnection();
InputStream input = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = input.read(buffer);
input.close();
return new String(buffer, 0, len);
}
jstring httpGet(jstring url) {
jenny::LocalRef<jstring> url(_url, false);
URLProxy url = URLProxy::newInstance(url);
URLConnectionProxy conn = url.openConnection();
InputStreamProxy input = conn.getInputStream();
jenny::LocalRef<jbyteArray> buffer(env->NewByteArray(1024));
jint len = input.read(buffer);
input.close();
return reinterpret_cast<jstring>(StringProxy::newInstance(env, buffer, 0, len).release);
}
jstring httpGet(JNIEnv *env, jclass clazz, jstring _url) {
jclass URLClass = env->FindClass("java/net/URL");
jmethodID URLClass_init3 = env->GetMethodID(URLClass, "<init>", "(Ljava/lang/String;)V");
jmethodID URLClass_openConnection =
env->GetMethodID(URLClass, "openConnection", "()Ljava/net/URLConnection;");
auto url = env->NewObject(URLClass, URLClass_init3, _url);
auto conn = env->CallObjectMethod(url, URLClass_openConnection);
jclass URLConnectionClass = env->FindClass("java/net/URLConnection");
jmethodID URLConnectionClass_getInputStream =
env->GetMethodID(URLConnectionClass, "getInputStream", "()Ljava/io/InputStream;");
jclass InputStreamClass = env->FindClass("java/io/InputStream");
jmethodID InputStreamClass_read = env->GetMethodID(InputStreamClass, "read", "([B)I");
jmethodID InputStreamClass_close = env->GetMethodID(InputStreamClass, "close", "()V");
auto input = env->CallObjectMethod(conn, URLConnectionClass_getInputStream);
jbyteArray buffer = env->NewByteArray(1024);
jint len = env->CallIntMethod(input, InputStreamClass_read, buffer);
env->CallVoidMethod(input, InputStreamClass_close);
jclass StringClass = env->FindClass("java/lang/String");
jmethodID StringClass_init = env->GetMethodID(StringClass, "<init>", "([BII)V");
jstring ret =
reinterpret_cast<jstring>(env->NewObject(StringClass, StringClass_init, buffer, 0, len));
env->DeleteLocalRef(URLClass);
env->DeleteLocalRef(URLConnectionClass);
env->DeleteLocalRef(InputStreamClass);
env->DeleteLocalRef(StringClass);
env->DeleteLocalRef(url);
env->DeleteLocalRef(input);
env->DeleteLocalRef(conn);
env->DeleteLocalRef(buffer);
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment