java怎么获取response返回内容

64次阅读
没有评论

共计 1781 个字符,预计需要花费 5 分钟才能阅读完成。

在 Java 中,可以使用 HTTPURLConnection 或 HttpClient 来获取 HTTP 响应的内容。
使用 HTTPURLConnection 的示例代码如下:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {public static void main(String[] args) {
try {URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为 GET
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {response.append(line);
}
reader.close();
System.out.println(response.toString());
} else {System.out.println("HTTP request failed. Response Code:" + responseCode);
}
connection.disconnect();} catch (Exception e) {e.printStackTrace();
}
}
}

使用 HttpClient 的示例代码如下:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class Main {public static void main(String[] args) {HttpClient httpClient = new DefaultHttpClient();
try {HttpGet httpGet = new HttpGet("http://example.com");
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
System.out.println(responseString);
} else {System.out.println("HTTP request failed. Response Code:" + statusCode);
}
} catch (Exception e) {e.printStackTrace();
} finally {httpClient.getConnectionManager().shutdown();}
}
}

这些代码示例使用 HTTP GET 请求来获取响应的内容,并将其打印到控制台。你可以根据实际需要进行修改和适配。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-16发表,共计1781字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)