java 通过发送json,post请求,返回json数据的方法
实例如下所示:
importjava.io.BufferedReader;
importjava.io.DataOutputStream;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.net.HttpURLConnection;
importjava.net.URL;
importorg.json.JSONArray;
importorg.json.JSONObject;
publicclassGetJsonData{
publicstaticStringgetJsonData(JSONObjectjsonParam,Stringurls){
StringBuffersb=newStringBuffer();
try{
;
//创建url资源
URLurl=newURL(urls);
//建立http连接
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
//设置允许输出
conn.setDoOutput(true);
//设置允许输入
conn.setDoInput(true);
//设置不用缓存
conn.setUseCaches(false);
//设置传递方式
conn.setRequestMethod("POST");
//设置维持长连接
conn.setRequestProperty("Connection","Keep-Alive");
//设置文件字符集:
conn.setRequestProperty("Charset","UTF-8");
//转换为字节数组
byte[]data=(jsonParam.toString()).getBytes();
//设置文件长度
conn.setRequestProperty("Content-Length",String.valueOf(data.length));
//设置文件类型:
conn.setRequestProperty("contentType","application/json");
//开始连接请求
conn.connect();
OutputStreamout=newDataOutputStream(conn.getOutputStream());
//写入请求的字符串
out.write((jsonParam.toString()).getBytes());
out.flush();
out.close();
System.out.println(conn.getResponseCode());
//请求返回的状态
if(HttpURLConnection.HTTP_OK==conn.getResponseCode(){
System.out.println("连接成功");
//请求返回的数据
InputStreamin1=conn.getInputStream();
try{
StringreadLine=newString();
BufferedReaderresponseReader=newBufferedReader(newInputStreamReader(in1,"UTF-8"));
while((readLine=responseReader.readLine())!=null){
sb.append(readLine).append("\n");
}
responseReader.close();
System.out.println(sb.toString());
}catch(Exceptione1){
e1.printStackTrace();
}
}else{
System.out.println("error++");
}
}catch(Exceptione){
}
returnsb.toString();
}
publicstaticvoidmain(String[]args){
JSONObjectjsonParam=newJSONObject();
jsonParam.put("id","1401_1406");
jsonParam.put("device_size","480x720");
Stringurl="www.baidu.com";
Stringdata=GetJsonData.getJsonData(jsonParam,url);
//返回的是一个[{}]格式的字符串时:
JSONArrayjsonArray=newJSONArray(data);
//返回的是一个{}格式的字符串时:
/*JSONObjectobj=newJSONObject(data);*/
}
}
以上这篇java通过发送json,post请求,返回json数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。