http请求返回json对象。简单的接口处理

4 篇文章 0 订阅

开发了一个独立查询存储的系统,需要被其他系统访问,记录一下方法 也许以后会用到。很简单的http请求和返回

package com.hz.contral;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.core.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hz.entity.Esentity;
import com.hz.entity.SoGoEntity;
import com.hz.entity.SoGoEntity;
import com.hz.entity.TrackBean;
import com.hz.service.ElasticsearchService;
import com.hz.service.HbaseService;
import com.hz.util.ConfigInfo;
import com.hz.util.PageUtils;

@Controller
public class ElasticsearchContral {

	
	
	//将查询值返回
	@RequestMapping("/searchPageJson")
	public void searchPageJson(HttpServletRequest request,HttpServletResponse response, Model model) throws IOException {
		String searchName = request.getParameter("search");
		String pageNum = request.getParameter("number");

    
	        //放入需要返回的值
		Map<String, Object> returnMap=new HashMap<String, Object>();
		 //转为json
		String jsonMap = JSON.toJSONString(returnMap,true); 
 
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(jsonMap);//返回json数值
		out.flush();
		out.close();
	}
	

	 

}

接下来是请求端的代码

package com.hz.util;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;

public class HttpTest {

	public static void main(String[] args) throws IOException {
	 
		post( );
		System.out.println("结束");
	}
	 
	
	private static void post() {
		 // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)  
		HttpURLConnection connection = null;
		// 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)  
		BufferedReader bf = null;
		StringBuilder sb = null;
		try {
			URL url = new URL("http://192.168.3.157:8080/HZ.Hbase/searchPageJson.html");  
			 
			 connection = (HttpURLConnection) url.openConnection();
			   
			 // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)  
			 connection.setDoOutput(true);  
			   
			 // 设置连接输入流为true  
			 connection.setDoInput(true);  
			   
			 // 设置请求方式为post  
			 connection.setRequestMethod("POST");  
			   
			 // post请求缓存设为false  
			 connection.setUseCaches(false);  
			   
			 // 设置该HttpURLConnection实例是否自动执行重定向  
			 connection.setInstanceFollowRedirects(true);  
			   
			 // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)  
			 // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据  
			 // ;charset=utf-8 必须要,不然妙兜那边会出现乱码【★★★★★】  
			 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");     
			   
			 // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)  
			 connection.connect();  
			   
			 // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)  
			 DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());  
			   
			 String app_key = "search="+ URLEncoder.encode("喜欢", "utf-8");        // 已修改【改为错误数据,以免信息泄露】  
			 String agt_num = "&number"+ URLEncoder.encode("1", "utf-8");              // 已修改【改为错误数据,以免信息泄露】  
			
			   
			 // 格式 parm = aaa=111&bbb=222&ccc=333&ddd=444  
			 String parm = app_key+ agt_num;  
			   
			 // 将参数输出到连接  
			 dataout.writeBytes(parm);  
			   
			 // 输出完成后刷新并关闭流  
			 dataout.flush();  
			 dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)   
			   
//         System.out.println(connection.getResponseCode());  
			   
			 bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));   
			 String line;  
			 sb = new StringBuilder();
			   
			 // 循环读取流,若不到结尾处  
			 while ((line = bf.readLine()) != null) {  
//             sb.append(bf.readLine());  
			     sb.append(line).append(System.getProperty("line.separator"));  
			 }
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				bf.close();
			} catch (IOException e) {
				e.printStackTrace();
			connection.disconnect(); // 销毁连接  
		}
         System.out.println(sb.toString());  
   
     }  
 
	}
}

一个简单的 http请求和返回就可以了。。。。仅供参考。自己留着备用。

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值