HTTP协议post请求返回json数据

  1. 有两种方式:大家详细看看,非常好用!

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.jingyou.application.common.JSONUtils;
public class HttpClientCheHuiTDH {
    public static String doPost(Map map)throws Exception {
		//1 获得HttpClient这个工具类
    	HttpClient client = HttpClients.createDefault();
    	//2 设置Http请求方式 (get,post)
    	HttpPost post = new HttpPost("http://36.110.41.67:8090/dwjk/api/getAjbsAndAh/getNAjbs");//getAh
    	post.setHeader("systemid", "jingyoutimes");
    	post.setHeader("authcode", "3699185f24ddaa775805d5c476701098");
    	//3 传递数据
    //	JSONObject response = null;
    	String jsonTDH = JSONUtils.bean2json(map);
    	System.out.println(jsonTDH);
        try {
          StringEntity s = new StringEntity(jsonTDH.toString());
          s.setContentEncoding("UTF-8");
          s.setContentType("application/json");//发送json数据需要设置contentType
          post.setEntity(s);
          HttpResponse res = client.execute(post);
          if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            HttpEntity entity = res.getEntity();
            String result = EntityUtils.toString(res.getEntity());// 返回json格式:
           // response = JSONObject.fromObject(result);
            System.out.println(result);
            return result;
          }
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
        return null;
    	
    	//NameValuePair  NJbfyPair = new BasicNameValuePair("NJbfy","2050");
    /*	NameValuePair  NJbfyPair = new BasicNameValuePair("NJbfy","1700");
    	List<NameValuePair> params = new ArrayList<NameValuePair>();
    	params.add(NJbfyPair);
    	HttpEntity sendEntity = new UrlEncodedFormEntity(params,"UTF-8");
    	post.setEntity(sendEntity);
    	//4 发送请求  并 接受响应
    	HttpResponse response = client.execute(post);
    	
    	 * HttpClient中 把请求 或 响应的数据 都称之为 HttpEntity;
    	 
    	HttpEntity entity = response.getEntity();
    	InputStream is = entity.getContent();
    	//开始 传统的IO操作
    	InputStreamReader isr =  new InputStreamReader(is,"UTF-8");
    	BufferedReader br  = new BufferedReader(isr);
    	String flag = null;
    	while(true){
    		flag = br.readLine();
    		if(flag==null)break;
    		System.out.println(flag);
    		return flag;
    	}
    	return flag;*/
	}
} 

猜你喜欢

转载自blog.csdn.net/nandao158/article/details/71091555