Java:下载字符串HTTP GET

wsxa1bj1  于 2023-09-29  发布在  Java
关注(0)|答案(4)|浏览(111)

下午好我需要的代码,将下载一个小的服务器字符串,我有服务器接收参数,并通过PHP返回值
网址:http://127.0.0.1/page.php?var=a
URL可以返回值“YES”或“NO”
我想对变量进行编码并返回值

67up9zun

67up9zun1#

您可以在一行hackey Java中完成此操作,而无需额外的库。就像这样:

String out = new Scanner(new URL(...).openStream(), "UTF-8").useDelimiter("\\A").next();
3mpgtkmj

3mpgtkmj2#

try (
  InputStream in = uri.openStream();
  FileOutputStream out = new FileOutputStream(outFile);
) {
  HttpURLConnection uriConn = (HttpURLConnection) uri.openConnection();
  int contentLength = uriConn.getHeaderFieldInt("Content-Length", -1);

  out.getChannel().transferFrom(Channels.newChannel(in),
                                outFile.length(),
                                contentLength);
} catch (IOException ex) {
  ex.printStackTrace();
}
cgvd09ve

cgvd09ve3#

你可以很容易地使用OkHttp不要忘记先导入
示例代码:

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

更多信息:http://square.github.io/okhttp/

wnrlj8wa

wnrlj8wa4#

对我来说,使用org.apache.commons.http一直是健壮的、轻量级的和用户友好的。通过向request添加一个头文件,您可以设置User-Agent表示客户端的操作系统和浏览器信息。此外,如果服务器对内容类型敏感,您可以为Content-type添加另一个头,例如application/json。如果使用任何身份验证库(如jwt),令牌也可以位于此处。

public class Client {

private static HttpClient CLIENT = HttpClientBuilder.create().build();
private static final String URL = "http://127.0.0.1/page.php?var=a";

public static void main(String[] args) throws IOException {
    Client client = new Client();
    System.out.println(client.requestBuilder(URL));
}

private String requestBuilder(String url) throws IOException {
    HttpGet request = new HttpGet(url);
    // Add headers: OS, Browser, Content-Type
    request.addHeader("User-Agent", "Linux");
    request.addHeader("Content-Type", "application/json");
    HttpResponse response = CLIENT.execute(request);
    BufferedReader reader = new BufferedReader(new 
    InputStreamReader(response.getEntity().getContent()));
    StringBuilder result = new StringBuilder();
    String line;
    while (Objects.nonNull(line = reader.readLine()))
        result.append(line);
    return result.toString();
}

希望能帮上忙。如果有什么不清楚的请随时联系我。

相关问题