httpclient 요청 http 데이터, json 맵 변환 실례

인스턴스는 다음과 같습니다.

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이 맵을 바꾸는 실례의 모든 내용입니다. 많은 응원 부탁드립니다~

좋은 웹페이지 즐겨찾기