`
xihuan&java
  • 浏览: 161669 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

urlconnection和httpclient

HP 
阅读更多
urlconnection:
String urlAddress = "http://192.168.1.102:8080/AndroidServer/login.do";
	URL url;
	HttpURLConnection uRLConnection;
	public UrlConnectionToServer(){

	}
	
	public String doGet(String username,String password){
		
		String getUrl = urlAddress + "?username="+username+"&password="+password;
		try {
			url = new URL(getUrl);
			uRLConnection = (HttpURLConnection)url.openConnection();
			InputStream is = uRLConnection.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String response = "";
			String readLine = null;
			while((readLine =br.readLine()) != null){
				//response = br.readLine();
				response = response + readLine;
			}
			is.close();
			br.close();
			uRLConnection.disconnect();
			return response;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}
	
	public String doPost(String username,String password){
		try {
			url = new URL(urlAddress);
			uRLConnection = (HttpURLConnection)url.openConnection();
			uRLConnection.setDoInput(true);
			uRLConnection.setDoOutput(true);
			uRLConnection.setRequestMethod("POST");
			uRLConnection.setUseCaches(false);
			uRLConnection.setInstanceFollowRedirects(false);
			uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			uRLConnection.connect();
			
			DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
			String content = "username="+username+"&password="+password;
			out.writeBytes(content);
			out.flush();
			out.close();
			
			InputStream is = uRLConnection.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String response = "";
			String readLine = null;
			while((readLine =br.readLine()) != null){
				//response = br.readLine();
				response = response + readLine;
			}
			is.close();
			br.close();
			uRLConnection.disconnect();
			return response;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}

httpclient:
 String urlAddress = "http://192.168.1.102:8080/qualityserver/login.do";
	 public HttpClientServer(){
			
		}
		
	public String doGet(String username,String password){
		
		String getUrl = urlAddress + "?username="+username+"&password="+password;
		HttpGet httpGet = new HttpGet(getUrl);
		HttpParams hp = httpGet.getParams();
		hp.getParameter("true");
		//hp.
		//httpGet.setp
		HttpClient hc = new DefaultHttpClient();
		try {
			HttpResponse ht = hc.execute(httpGet);
			if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				HttpEntity he = ht.getEntity();
				InputStream is = he.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				String response = "";
				String readLine = null;
				while((readLine =br.readLine()) != null){
					//response = br.readLine();
					response = response + readLine;
				}
				is.close();
				br.close();
				
				//String str = EntityUtils.toString(he);
				System.out.println("========="+response);
				return response;
			}else{
				return "error";
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "exception";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "exception";
		}
		
		
		
		
	}
	
	public String doPost(String username,String password){
		//String getUrl = urlAddress + "?username="+username+"&password="+password;
		HttpPost httpPost = new HttpPost(urlAddress);
		List params = new ArrayList();
		NameValuePair pair1 = new BasicNameValuePair("username", username);
		NameValuePair pair2 = new BasicNameValuePair("password", password);
		params.add(pair1);
		params.add(pair2);
		
		 
		HttpEntity he;
		try {
			he = new UrlEncodedFormEntity(params, "gbk");
			httpPost.setEntity(he);
			
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
		
		HttpClient hc = new DefaultHttpClient();
		try {
			HttpResponse ht = hc.execute(httpPost);
			//连接成功
			if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				HttpEntity het = ht.getEntity();
				InputStream is = het.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				String response = "";
				String readLine = null;
				while((readLine =br.readLine()) != null){
					//response = br.readLine();
					response = response + readLine;
				}
				is.close();
				br.close();
				
				//String str = EntityUtils.toString(he);
				System.out.println("=========&&"+response);
				return response;
			}else{
				return "error";
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "exception";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "exception";
		}
		
	}


servlet端json转化:
resp.setContentType("text/json");
		resp.setCharacterEncoding("UTF-8");
		toDo = new ToDo();
		List<UserBean> list = new ArrayList<UserBean>();
			list = toDo.queryUsers(mySession);
			String body;
		try
		{
			//设定JSON
			JSONArray array = new JSONArray();
			for(UserBean bean : list)
			{
				JSONObject obj = new JSONObject();
				try
				{
					obj.put("username", bean.getUserName());
					obj.put("password", bean.getPassWord());
				}catch(Exception e){}
				array.add(obj);
			}
			pw.write(array.toString());
			System.out.println(array.toString());

android端接收:
String urlAddress = "http://192.168.1.102:8080/qualityserver/result.do";
		String body = 
			getContent(urlAddress);
		JSONArray array = new JSONArray(body);			
		for(int i=0;i<array.length();i++)
		{
			obj = array.getJSONObject(i);
			sb.append("用户名:").append(obj.getString("username")).append("\t");
			sb.append("密码:").append(obj.getString("password")).append("\n");
			
			HashMap<String, Object> map = new HashMap<String, Object>();
        	try {
				userName = obj.getString("username");
				passWord = obj.getString("password");
			} catch (JSONException e) {
				e.printStackTrace();
			}
        	map.put("username", userName);
        	map.put("password", passWord);
        	listItem.add(map);
			
		}
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        if(sb!=null)
        {
        	showResult.setText("用户名和密码信息:");
        	showResult.setTextSize(20);
        } else
			extracted();
 
       //设置adapter 
        SimpleAdapter simple = new SimpleAdapter(this,listItem,
        		android.R.layout.simple_list_item_2,
        		new String[]{"username","password"},
        		new int[]{android.R.id.text1,android.R.id.text2});
        listResult.setAdapter(simple);
        
        listResult.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				int positionId = (int) (id+1);
				Toast.makeText(MainActivity.this, "ID:"+positionId, Toast.LENGTH_LONG).show();
			
			}
		});
    }
	private void extracted() {
		showResult.setText("没有有效的数据!");
	}
	//和服务器连接
    private String getContent(String url)throws Exception{
    	StringBuilder sb = new StringBuilder();
    	HttpClient client =new DefaultHttpClient();
    	HttpParams httpParams =client.getParams();
    	
    	HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
    	HttpConnectionParams.setSoTimeout(httpParams, 5000);
    	HttpResponse response = client.execute(new HttpGet(url));
    	HttpEntity entity =response.getEntity();
    	
    	if(entity !=null){
    		BufferedReader reader = new BufferedReader(new InputStreamReader
    				(entity.getContent(),"UTF-8"),8192);
    		String line =null;
    		while ((line= reader.readLine())!=null){
    			sb.append(line +"\n");
    		}
    		reader.close();
    	}
    	return sb.toString();
    }

数据库查询信息:
 while(rs.next())
                {
                	UserBean bean = new UserBean();
                	bean.setUserName(rs.getString(1));
                	bean.setPassWord(rs.getString(2));
                	list.add(bean);
                }
                return list;
分享到:
评论

相关推荐

    HttpURLConnection和HTTPClient的比较,以及使用规则

    NULL 博文链接:https://xiaowei-qi-epro-com-cn.iteye.com/blog/1973295

    Web Service Tester

    【描述】Web Service Tester是一个针对Android 2.0平台的Eclipse工程,它演示了如何使用URLConnection和HttpClient两种方法来执行对WebService的GET和POST请求。这个工具对于开发者来说,是理解和实践网络通信的重要...

    httpClient和URLConnection的区别

    在Android应用开发中,进行网络通信是常见的任务,其中两种主要的请求方式是使用`HttpURLConnection`和`HttpClient`。虽然两者都能实现HTTP通信,但它们在功能、使用方式和性能上存在一些区别。 首先,Apache ...

    java实例技术手册

    此外,Java的网络API如URL、URLConnection和HTTPClient等,可用于构建Web服务和客户端应用。 J2EE技术是企业级Java应用的基石,涵盖了诸如Servlet、JSP(JavaServer Pages)、EJB(Enterprise JavaBeans)和JPA...

    网络编程(小知识点)_java_

    在实际应用中,我们还会遇到URL、URLConnection和HTTPClient等类,它们用于处理HTTP协议,方便我们访问Web资源。例如,可以通过URL建立与Web服务器的连接,使用URLConnection发送GET或POST请求,获取响应内容。 ...

    Java2范例入门与提高

    此外,Java的URL、URLConnection和HTTPClient类使得访问和处理Web资源变得简单。本书将详细讲解如何使用这些工具进行TCP/IP通信、HTTP请求和响应,以及如何实现简单的Web服务和客户端应用。 在实际示例部分,读者将...

    115个Java经典面试题和答案

    - URL、URLConnection和HttpClient用于网络请求。 9. **设计模式** - 单例模式、工厂模式、装饰器模式、代理模式等23种设计模式的解释和应用实例。 10. **Spring框架** - Spring的核心模块:Core、DI、AOP、MVC...

    java.net.URLConnection发送HTTP请求与通过Apache HttpClient发送HTTP请求比较

    总结来说,`java.net.URLConnection`适合简单、轻量级的HTTP请求,而Apache HttpClient更适合需要处理复杂HTTP逻辑和高性能需求的场景。开发人员应根据项目需求和自身技术水平来选择合适的方法。对于初学者,可以先...

    JAVA入门基础课件.zip

    此外,还会讲解URL、URLConnection和HTTPClient,用于获取和发送网络资源。 多线程是Java的一个强大特性,它允许程序同时执行多个任务。课程会讲解线程的创建、同步和通信,如synchronized关键字、wait/notify机制...

    java 面试题

    了解HTTP协议,特别是Java的URLConnection和HttpClient库。 十、设计模式 熟练掌握常见的设计模式,如工厂模式、单例模式、观察者模式、装饰器模式、适配器模式等,并能结合实际问题灵活运用。 通过以上知识点的...

    java葵花宝典,呕血力作

    此外,还会讲解URL、URLConnection和HTTPClient的使用,以实现网络数据的发送和接收。 最后,书中还将涵盖Java的反射机制,允许程序在运行时动态获取类的信息并操作类的对象。此外,还将探讨Java注解(Annotation)...

    tarena01 代码

    此外,URL、URLConnection和HttpClient类可以帮助我们处理网络请求和响应。 3. **Swing**: Swing是Java GUI(图形用户界面)库的一部分,用于构建桌面应用。它包含一系列组件,如JFrame、JButton、JLabel等,以及...

    ThinkinginJava

    此外,URL、URLConnection 和 HTTPClient 等类则方便进行 HTTP 协议的网络访问。 6. **输入/输出流**:Java I/O 流系统是处理数据输入和输出的基础,包括字符流和字节流,以及各种缓冲流、转换流和对象序列化。...

    java面试题--java面试题

    8. **网络编程**:了解Java的Socket编程,TCP/IP协议,HTTP协议,以及Java的网络类库如URLConnection和HttpClient,这些都是开发网络应用的基础。 9. **设计模式**:23种设计模式是软件工程的通用解决方案,面试中...

    JAVA面试题(收集整理Word版)

    7. **网络编程**:TCP和UDP协议的理解,Socket编程,ServerSocket的使用,HTTP协议基础,以及Java的URL、URLConnection和HttpClient类。 8. **设计模式**:面试中常见的是单例、工厂、抽象工厂、建造者、适配器、...

    j2se中文api.rar

    此外,URL、URLConnection 和 HTTPClient 类可用于访问和操作网络资源。 4. **多线程**:Java 中的 Thread 类和 Runnable 接口用于实现并发执行。线程同步机制包括 synchronized 关键字、wait()、notify() 和 ...

    Android网络处理

    3. **URLConnection和HttpClient**:早期的Android开发中,HttpURLConnection是官方推荐的API,但其使用相对复杂。HttpClient虽然已被弃用,但在某些场景下仍被广泛使用,因其易用性和灵活性。 二、Android网络访问...

    Java程序员面试宝典与习题

    理解URL、URLConnection和HttpClient的使用,以及HTTP协议的基本原理。 9. **数据库操作**:熟悉JDBC,包括连接数据库、执行SQL、处理结果集、事务管理等。了解ORM(Object-Relational Mapping)框架,如Hibernate...

    java课件ppt(其中包含了基础到网络开发)

    - **网络API**:Java的java.net包提供的网络编程接口,如URL、URLConnection和HttpClient,用于网络数据的获取和发送。 6. **Java EE与Web开发** - **Servlet**:学习Servlet的生命周期,以及如何处理HTTP请求和...

Global site tag (gtag.js) - Google Analytics