httpclient 请求http数据,json转map的实例
实例如下:
packagecom.idc.dataAudit.dataResource; importjava.util.ArrayList; importjava.util.HashMap; importjava.util.Iterator; importjava.util.List; importjava.util.Map; importnet.sf.json.JSONArray; importnet.sf.json.JSONObject; importorg.apache.commons.httpclient.HttpClient; importorg.apache.commons.httpclient.HttpMethod; importorg.apache.commons.httpclient.methods.GetMethod; publicclassRequestHttpManage{ publicMap<Integer,String>RequesthttpInfo(Stringurl){ StringresultStr=null; Map<Integer,String>mapResult=newHashMap<Integer,String>(); try{ HttpClientclient=newHttpClient(); HttpMethodmethod=newGetMethod(url); //使用POST方法 //HttpMethodmethod=newPostMethod("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(Exceptione){ e.printStackTrace(); } System.out.println(mapResult); returnmapResult; } publicMap<String,List<String>>GetMapFromJson(StringjsonStr){ Map<String,List<String>>mapResult=newHashMap<String,List<String>>(); try{ JSONObjectresult=JSONObject.fromObject(jsonStr);//转换为JSONObject JSONArraynameList=result.getJSONArray("result");//获取JSONArray intlength=nameList.size(); for(inti=0;i<length;i++){ JSONObjecttempObject=nameList.getJSONObject(i); Iteratoriter=tempObject.keys(); Stringkey=(String)iter.next(); StringkeyId=tempObject.getString(key); List<String>objList=newArrayList<String>(); for(;iter.hasNext();){ StringkeyLocal=(String)iter.next(); //System.out.println(key+"="+tempObject.getString(keyLocal)); objList.add(tempObject.getString(keyLocal)); } mapResult.put(keyId,objList); } }catch(Exceptione){ e.printStackTrace(); } System.out.println(mapResult); returnmapResult; } }
以上就是小编为大家带来的httpclient请求http数据,json转map的实例全部内容了,希望大家多多支持毛票票~