[英]How can I retrieve the response from an http get request in Java WITHOUT BufferedReader
I know there are thousands of articles and Q&A which teach me how to send an HTTP request in Java.我知道有数以千计的文章和问答教我如何用 Java 发送 HTTP 请求。 But all of them use a BufferedReader to read the response from server.但是它们都使用 BufferedReader 来读取来自服务器的响应。
I don't want to use a BufferedReader , because I encountered an " OutOfMemoryError " when using it on my android project.我不想使用 BufferedReader ,因为在我的 android 项目中使用它时遇到了“ OutOfMemoryError ”。 I don't know why this happened while others succeed, but it was certainly caused by BufferedReader after a long time of debugging and I am really tired of this issue.我不知道为什么会发生这种情况,而其他人却成功了,但这肯定是经过长时间调试后由 BufferedReader 引起的,我真的厌倦了这个问题。 Is there any way to retrieve the response other than creating a new BufferedReader object?除了创建新的 BufferedReader 对象之外,还有什么方法可以检索响应? I just want to send a simplest get request, and get the response which provides HTML content,not considering efficiency.我只想发送一个最简单的 get 请求,并获取提供 HTML 内容的响应,而不考虑效率。
Use OkHttp for efficient network access使用 OkHttp 进行高效的网络访问
What is OkHTTP? OkHTTP 是什么? OkHTTP is an open source project designed to be an efficient HTTP client. OkHTTP 是一个开源项目,旨在成为一个高效的 HTTP 客户端。
// avoid creating several instances, should be singleon
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.vogella.com/index.html")
.build();
You can also add parameters您还可以添加参数
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://api.github.help").newBuilder();
urlBuilder.addQueryParameter("v", "1.0");
urlBuilder.addQueryParameter("user", "vogella");
String url = urlBuilder.build().toString();
Request request = new Request.Builder()
.url(url)
.build();
source https://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html来源https://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html
You can use Volley for that.为此,您可以使用 Volley。 It's fast, fluid and lightweight.它快速、流畅且轻便。
In your build.gradle file, add this line and compile:在你的 build.gradle 文件中,添加这一行并编译:
implementation 'com.android.volley:volley:1.1.1'
Make a network singleton制作网络单例
public class NetworkSingleton {
private static NetworkSingleton instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private static Context ctx;
private NetworkSingleton(Context context) {
ctx = context;
requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized NetworkSingleton getInstance(Context context) {
if (instance == null) {
instance = new NetworkSingleton(context);
}
return instance;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
requestQueue = Volley.newRequestQueue(ctx.getApplicationContext());
}
return requestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
Make a String Request:发出字符串请求:
StringRequest stringRequest = new StringRequest(Request.Method.GET, "URL to fetch",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//This is executed after successful response to URL
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//If error occurs
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Add a header to request");
return params;
}
};
NetworkSingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
Read more about volley at:阅读更多关于排球的信息:
https://developer.android.com/training/volley
You can use InputStream
您可以使用InputStream
Eg:例如:
HttpURLConnection conn=(HttpURLConnection)(new URL(your URL).openConnection());
InputStream is=conn.getInputStream();
String str=new String(is.readAllBytes());
is.close();
return str;
Or Java 11 HttpClient
API.或 Java 11 HttpClient
API。
Eg:例如:
HttpClient client=HttpClient.newHttpClient();
HttpRequest request=HttpRequest.newBuilder().uri(new URI(your URL)).GET().build();
HttpResponse<String> response=client.send(request,BodyHandlers.ofString());
return response.body();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.