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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자바 양력 전 음력 도구 류자바 양력 이 음력 으로 바 뀌 는 도구 류 인터넷 에는 많은 것들 이 있 습 니 다. 대체적으로 같은 소스 코드 에서 나 왔 지만 이런 소스 코드 는 프로젝트 요 구 를 만족 시 키 지 못 하고 시간 을 제공 하 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.