本文主要是介绍Java http请求示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用HttpURLConnection
public static String httpGet(String host) {HttpURLConnection connection = null;try {URL url = new URL(host);connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setDoOutput(true);InputStream is = connection.getInputStream();BufferedReader rd = new BufferedReader(new InputStreamReader(is));StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+String line;while ((line = rd.readLine()) != null) {response.append(line);response.append('\n');}rd.close();return response.toString();} catch (Exception e) {e.printStackTrace();return null;} finally {if (connection != null) {connection.disconnect();}}
}public static String httpPost(String host) {HttpURLConnection connection = null;try {URL url = new URL(host);connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("POST");connection.setRequestProperty("Content-Type", "application/json");connection.setDoOutput(true);//Send requestDataOutputStream wr = new DataOutputStream(connection.getOutputStream());wr.write(body);wr.close();//Get ResponseInputStream is = connection.getInputStream();BufferedReader rd = new BufferedReader(new InputStreamReader(is));StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+String line;while ((line = rd.readLine()) != null) {response.append(line);response.append('\r');}rd.close();return response.toString();} catch (Exception e) {e.printStackTrace();return null;} finally {if (connection != null) {connection.disconnect();}}
}
使用OkHttp
public static String httpGet(String url) {String result = null;OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url(url).build();try {Response response = client.newCall(request).execute();result = response.body().string();} catch (Exception e) {e.printStackTrace();}return result;
}public static String httpPost(String url, byte[] body) {String result = null;OkHttpClient httpClient = new OkHttpClient();RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-protobuf"), body);Request request = new Request.Builder().addHeader("Content-Type", "application/x-protobuf").url(url).post(requestBody).build();try {Response response = httpClient.newCall(request).execute();result = response.body().string();} catch (IOException e) {e.printStackTrace();}return result;
}
这篇关于Java http请求示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!