httpClient他のWebアクセス情報

3430 ワード

この例はHttpClient技術を採用し、Jsonによってデータを処理し、インスタンスコード:
送信者がデータを送信して受信する:
public static JSONObject postHttpClient(String url,JSONObject json) throws Exception{
		//      HttpClient   
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        JSONObject response = null;
        try {
        	StringEntity s = new StringEntity(json.toString());
			s.setContentEncoding("UTF-8");
			s.setContentType("application/json");
			httpPost.setEntity(s);
			System.out.println("execurting request:" + httpPost.getURI());
			
            HttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            System.out.println(httpResponse.getStatusLine().getStatusCode());
            //    
	    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            	HttpEntity entity = httpResponse.getEntity();
				String charset = EntityUtils.getContentCharSet(entity);
				String jsonStr = "";
				BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),charset));
				String temp = reader.readLine();
				 while(temp!=null){
					 jsonStr+=temp;
					 temp = reader.readLine();
				}
				response = JSONObject.fromObject(jsonStr);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            log.debug(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.debug(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            log.debug(e.getMessage());
        } finally {
            //    ,    
            httpClient.getConnectionManager().shutdown();
        }
        return response;
	}

受信者はデータを受信し、次のように返します.
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		StringBuffer sb = new StringBuffer();
		String line = null;
		List<XxtsDomain> dataList = null;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null){
				sb.append(line);
			}
			JSONObject jsonObject = JSONObject.fromObject(sb.toString());
			JSONArray array = jsonObject.getJSONArray("dataList");
			dataList = JSONArray.toList(array, new XxtsDomain(), new JsonConfig());
			for (XxtsDomain xxtsDomain: dataList) {
				if(postTsxxOne(xxtsDomain)){
					xxtsDomain.setSendBool(true);
				}else{
					xxtsDomain.setSendBool(false);
				}
			}
		} catch (Exception e) {}
		
		//   
         response.setContentType("text/html;charset=UTF-8");   
        PrintWriter out = response.getWriter();
        XxtsAllDomain xxtsAll = new XxtsAllDomain();
	xxtsAll.setDataList(dataList);
	JSONObject jsonList = JSONObject.fromObject(xxtsAll);  
        out.println(jsonList.toString());
	out.flush();
        out.close();
	}   	

jsonセクションは別の記事を参照できます