java http 보 내기 post 요청 - json 형식

3578 단어 자바 도구
최근 프로젝트 에서 위 챗 백 스테이지 에 요청 을 보 냈 습 니 다. 인터넷 의 많은 도구 에 문제 가 있 습 니 다. 자신 이 그 중의 하나 에 따라 최적화 시 켜 코드 를 직접 올 렸 습 니 다.
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;


public static String doPost(String url, String json) {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);
    String result = null;
    try {
        StringEntity s = new StringEntity(json,"utf-8");
        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) {
            if (res.getEntity().isStreaming() && "image/jpeg".equals(res.getEntity().getContentType().getValue())){
                File file = new File("C:/Users/Administrator/Desktop/5.jpg");
                if (!file.exists()){
                    file.createNewFile();
                }
                OutputStream outputStream = new FileOutputStream(file);
                res.getEntity().writeTo(outputStream);
                outputStream.flush();
                return "ojbk";
            }
            result = EntityUtils.toString(res.getEntity());//   json  :

        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            client.close();
        } catch (IOException e) {
            log.error("【post  】   IOException = ", e);
        }
    }
    return result;
}

        이 인자 json 은 json 형식의 문자열 입 니 다.
        필요 하 다 면 돌아 오 는 Content - Type 에 따라 해당 하 는 처 리 를 할 수 있 습 니 다.
        간단 한 용법, 예 를 들 어 애플 릿 의 QR 코드 를 가 져 오고 위 챗 사용자 에 게 템 플 릿 메 시 지 를 보 내 는 것:
    public static void main(String[] args) {
        String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=  APPID&secret=  APPSECRET";
        String s = UrlUtil.get(token_url);
        Map getResult = (Map) JSON.parse(s);
        String accessToken = (String) getResult.get("access_token");
        Map map = new HashMap();
        map.put("scene","310");
        map.put("page","pages/login/main");
        //         
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
        String s1 = UrlUtil.doPost(url, JSON.toJSONString(map));
        System.out.println(s1);

        Map m = new HashMap();
        m.put("page","http://");
        m.put("template_id","fkdsajlfjk");
        m.put("touser","dfkljskaijf");
        m.put("form_id","jkdfj8923ur022ewro30");
        m.put("keyword1", "******");
        /*****    ****/
        
        //        
        String url2 = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+accessToken;
        String s2 = UrlUtil.doPost(url2, JSON.toJSONString(m));
        System.out.println(s2);
    }

        애플 릿 의 QR 코드 반환 형식 가 져 오기 Content - type = image / jpeg
        메 시 지 를 보 낸 Content - type = iapplication / json;encoding=utf-8
 
 
 

좋은 웹페이지 즐겨찾기