访问HTTP网址的两种方式

1、使用HttpClient:网络

NameValuePair username = new BasicNameValuePair("username", "zhangsan");
NameValuePair password = new BasicNameValuePair("password","1qaz2wsx");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(username);
params.add(password);
String validateURL = "http://10.1.1.0:8080/dbconnect/ConnectServlet";编码

try {url

        HttpParams httpParams = new BasicHttpParams();code

        HttpConnectionParams.setConnectionTimeout(httpParams,5000); //设置链接超时为5秒orm

        HttpClient client = new DefaultHttpClient(httpParams); // 生成一个http客户端发送请求对象对象

        HttpPost httpPost = new HttpPost(urlString); //设定请求方式字符串

          if (params!=null && params.size()!=0) {
              //把键值对进行编码操做并放入HttpEntity对象中
              httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
           }get

        HttpResponse httpResponse = client.execute(httpPost); // 发送请求并等待响应input

          // 判断网络链接是否成功
          if (httpResponse.getStatusLine().getStatusCode() != 200) {
             System.out.println("网络错误异常!");
           }else{it

             HttpEntity entity = httpResponse.getEntity(); // 获取响应里面的内容
             inputStream = entity.getContent();  // 获得服务气端发回的响应的内容(都在一个流里面)
             // 获得服务气端发回的响应的内容(都在一个字符串里面)
             String strResult = EntityUtils.toString(entity); 

             System.out.println(strResult);

       }

      } catch (Exception e) {
         e.printStackTrace();
  }

 

2、使用HttpURLConnection:

String validateUrl="http://10.1.1.0:8080/dbconnect/ConnectServlet?username=zhangsan&password=1qaz2wsx";

try {

       URL url = new URL(validateUrl); //建立URL对象

       //返回一个URLConnection对象,它表示到URL所引用的远程对象的链接

       HttpURLConnection conn = (HttpURLConnection) url.openConnection();

       conn.setConnectTimeout(5000); //设置链接超时为5秒

       conn.setRequestMethod("GET"); //设定请求方式

       conn.connect(); //创建到远程对象的实际链接

       //返回打开链接读取的输入流

       BufferedInputStream dis = new BufferedInputStream(conn.getInputStream());        

      //判断是否正常响应数据 

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
           System.out.println("网络错误异常!");
       }else{

       //读取数据流      

     byte[] contents = new byte[1024];  

      int byteRead = 0;  

      String strFileContents;  

      try {  

               while((byteRead = dis.read(contents)) != -1){  

                strFileContents = new String(contents,0,byteRead);  

                System.out.println(strFileContents);  

           }  catch (IOException e) {  

            e.printStackTrace();  

        }  

        dis.close();

}

} catch (Exception e) {    e.printStackTrace();   } finally {     if (conn != null) {      conn.disconnect(); //中断链接     }  }

相关文章
相关标签/搜索