欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

httpclient 请求http数据,json转map的实例

程序员文章站 2024-03-09 14:54:11
实例如下: package com.idc.dataaudit.dataresource; import java.util.arraylist; i...

实例如下:

package com.idc.dataaudit.dataresource;


import java.util.arraylist;
import java.util.hashmap;
import java.util.iterator;
import java.util.list;
import java.util.map;


import net.sf.json.jsonarray;
import net.sf.json.jsonobject;


import org.apache.commons.httpclient.httpclient;
import org.apache.commons.httpclient.httpmethod;
import org.apache.commons.httpclient.methods.getmethod;


public class requesthttpmanage {
	public map<integer,string> requesthttpinfo(string url) { 
		string resultstr = null;
		map<integer,string> mapresult = new hashmap<integer,string>();
  	try{
			httpclient client = new httpclient();  
			httpmethod method=new getmethod(url); 
			//使用post方法 
			//httpmethod method = new postmethod("http://java.sun.com"); 
			client.executemethod(method); 
			
			//打印服务器返回的状态 
			//system.out.println(method.getprotocolversion());
			//system.out.println(method.getstatusline().getstatuscode());
			//system.out.println(method.getstatusline().getreasonphrase());
			  // system.out.println(method.getstatusline().tostring());
			  // system.out.println(method.getstatusline()); 
			//打印返回的信息 
			  // system.out.println(method.getresponsebodyasstring()); 
			
			
			mapresult.put(method.getstatusline().getstatuscode(), method.getresponsebodyasstring());
			//释放连接 
			method.releaseconnection(); 
  	}catch(exception e){
  		e.printstacktrace();
  	}
  	system.out.println(mapresult);
  	return mapresult;
  } 
	public map<string,list<string>> getmapfromjson(string jsonstr){
  	map<string,list<string>> mapresult = new hashmap<string,list<string>>();
  	try{
  		
  		 jsonobject result = jsonobject.fromobject(jsonstr);//转换为jsonobject
      
       jsonarray namelist = result.getjsonarray("result");//获取jsonarray
       int length = namelist.size();
       for(int i=0;i<length;i++){
      	 jsonobject tempobject = namelist.getjsonobject(i);
      	 
      	 iterator iter = tempobject.keys();
      	 string key = (string)iter.next();
      	 
      	 
      	 string keyid = tempobject .getstring(key);
      	 
      	 list<string> objlist = new arraylist<string>();
      	 for (; iter.hasnext();) { 
      	    string keylocal = (string)iter.next();
      	  //  system.out.println(key+"="+tempobject .getstring(keylocal));
      	    objlist.add(tempobject .getstring(keylocal));
      	 }
      	 mapresult.put(keyid, objlist);
       }
  	}catch(exception e){
  		e.printstacktrace();
  	}
  	system.out.println(mapresult);
  	return mapresult;
  }


 
}

以上就是小编为大家带来的httpclient 请求http数据,json转map的实例全部内容了,希望大家多多支持~