使用流的方式去进行post请求解决中文乱码问题返回xml格式

本文介绍了一个使用Java发送HTTP POST请求的具体实现方法,包括设置请求头、请求参数、读取响应等步骤,并提供了完整的代码示例。

/**
* 请求post
* @Title: getHttpURLConnection
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param: @param url1
* @param: @param paream
* @param: @return
* @param: @throws IOException
* @param: @throws JSONException
* @return: String
* @throws
* @author ecar
* @Date 2016-7-23 下午03:08:59
*/
private String getHttpURLConnection(String url1,String paream) throws IOException, JSONException
{
Long deviceId=1l;
URL url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
connection.setConnectTimeout(80*1000);
connection.setReadTimeout(80*1000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeLong(deviceId);
//最短
JSONArray array = new JSONArray(paream);
out.writeShort(array.length());
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
out.write(obj.getString("time").getBytes("UTF8"));
double d = obj.getDouble("lon");
int lon = (int)(d * 1000000);
out.writeInt(lon);
d = obj.getDouble("lat") ;
int lat = (int)(d * 1000000);
out.writeInt(lat);
out.writeFloat((float)obj.getDouble("speed"));
out.writeFloat((float)obj.getDouble("direc"));
}

调用方式:

String ss = "[" ;
String date = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date());
Gps gps= PositionUtil.gcj_To_Gps84(Double.valueOf(split[1]), Double.valueOf(split[0]));//转化为84的坐标系
Gps gps1= PositionUtil.gcj_To_Gps84(Double.valueOf(split02[1]), Double.valueOf(split02[0]));//转化为84的坐标系
Gps gps2= PositionUtil.gcj_To_Gps84(Double.valueOf(split03[1]), Double.valueOf(split03[0]));//转化为84的坐标系
ss+="{\"time\":\""+date+"\",\"lon\":"+gps.getWgLon()+",\"lat\":"+gps.getWgLat()+",\"speed\":20,\"direc\":0},";
ss+="{\"time\":\""+date+"\",\"lon\":"+gps1.getWgLon()+",\"lat\":"+gps1.getWgLat()+",\"speed\":30,\"direc\":0},";
ss+="{\"time\":\""+date+"\",\"lon\":"+gps2.getWgLon()+",\"lat\":"+gps2.getWgLat()+",\"speed\":30,\"direc\":0}";
ss+="]";
String param=getHttpURLConnection(uriAPI+"/RouteTrafficInfoSearch?bizcode=fBAym29ZX11kVKbuQVnJ",ss);
System.out.println(param);

返回xml格式的数据

out.flush();
out.close();
DataInputStream in = new DataInputStream(connection.getInputStream());
int len = in.available();
byte[] b = new byte[len];
in.read(b);
// System.out.println(new String(b,"utf-8"));
return new String(b,"utf-8");
}

转载于:https://www.cnblogs.com/liuying1995/p/5729155.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值