用httpPost对JSON发送和接收的例子

论坛 期权论坛 脚本     
匿名网站用户   2020-12-21 09:08   58   0

HTTPPost发送JSON:

privatestaticfinalStringAPPLICATION_JSON="application/json";

privatestaticfinalStringCONTENT_TYPE_TEXT_JSON="text/json";

publicstaticvoidhttpPostWithJSON(Stringurl,Stringjson)throwsException{
//将JSON进行UTF-8编码,以便传输中文
StringencoderJson=URLEncoder.encode(json,HTTP.UTF_8);

DefaultHttpClienthttpClient=newDefaultHttpClient();
HttpPosthttpPost=newHttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE,APPLICATION_JSON);

StringEntityse=newStringEntity(encoderJson);
se.setContentType(CONTENT_TYPE_TEXT_JSON);
se.setContentEncoding(newBasicHeader(HTTP.CONTENT_TYPE,APPLICATION_JSON));
httpPost.setEntity(se);
httpClient.execute(httpPost);
}


接收HTTPPost中的JSON:

publicstaticStringreceivePost(HttpServletRequestrequest)throwsIOException,UnsupportedEncodingException{

//读取请求内容
BufferedReaderbr=newBufferedReader(newInputStreamReader(request.getInputStream()));
Stringline=null;
StringBuildersb=newStringBuilder();
while((line=br.readLine())!=null){
sb.append(line);
}


//将资料解码
StringreqBody=sb.toString();
returnURLDecoder.decode(reqBody,HTTP.UTF_8);
}
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP