本文参考作者:超超boy 链接:https://www.cnblogs.com/jycboy/p/post01.html
一、在android用Get方式发送http请求,使用的是java标准类。
主要步骤:
1.构造URL
URL url = new URL(String path);
2.设置连接
httpURLConnection = (HttpURLConnection) url.openConnection();
//设置超时时间
httpURLConnection.setConnectTimeout(3000);
//设置请求使用GET方式
httpURLConnection.setRequestMethod("GET");
int responsecode = httpURLConnection.getResponseCode();//返回至为响应编号,如:HTTP_OK表示连接成功。
3.获取返回数据
if(responsecode == HttpURLConnection.HTTP_OK){
inputStream = httpURLConnection.getInputStream();
}
new InputStreamReader(inputStream,"utf-8")
4.关闭连接
void disconnect()
二、在Eclipse中创建Demo实现get方式的请求的逻辑代码:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class HttpUtils { private static String URL_PATH="http://www.baidu.com"; private static HttpURLConnection httpURLConnection = null; public HttpUtils(){} public static void main(String[] args){ shuchu(); } public static void shuchu(){ InputStream inputStream = getInputStream(); String result; try { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8")); result = ""; String line = ""; try { while((line = reader.readLine())!= null){ result = result+ line; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(result); httpURLConnection.disconnect(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 获取服务端的数据,以InputStream返回 * @return */ public static InputStream getInputStream(){ InputStream inputStream = null; try { URL url = new URL(URL_PATH); if(url != null){ try { httpURLConnection = (HttpURLConnection) url.openConnection(); //设置超时时间 httpURLConnection.setConnectTimeout(3000); //设置请求方式 httpURLConnection.setRequestMethod("GET"); int responsecode = httpURLConnection.getResponseCode(); if(responsecode == HttpURLConnection.HTTP_OK){ inputStream = httpURLConnection.getInputStream(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return inputStream; } }