核心代码:
<span style="font-size:18px;">private String mythrid(){
String jsonStr = null;
try {
final JSONObject jsonObject = new JSONObject();
jsonObject.put("2", "金色");
// json字符串
String jsonObjectStr =jsonObject.toString();
// 把json字符串要重新编码,否则在拼接在路径中,会出现乱码
String jsonObjectStrEncoder = URLEncoder.encode(jsonObjectStr, "utf-8");
// 连接网络6句话
String path = "http://www.5ulm.cn/ws/product/getProdDetailByAttrs?keyAttrRefSaleAttrId=1&saleAttrs="+jsonObjectStrEncoder;
Log.e("1","请求路径:"+path);
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");// 设置请求的方式
connection.setReadTimeout(5000);// 设置超时的时间
connection.setConnectTimeout(5000);// 设置链接超时的时间
connection.setRequestProperty("Referer",path);
connection.setRequestProperty("Accept-Charset", "UTF-8");
// 设置请求的头
connection
.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");
if (connection.getResponseCode() == 200) {
System.out.println("连接成功" + ">>>>>>>>>>>");
// 用getInputStream流直接获得json的数据
InputStream is = connection.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bs = new byte[1024];
int len = 0;
while ((len = is.read(bs)) != -1) {
bos.write(bs, 0, len);
}
// 字节流对象转化成字节数组
byte[] bosData = bos.toByteArray();
// 字节数组转化成字符串然后进行解析
jsonStr= new String(bosData, "UTF-8");
Log.e("1","服务器返回的数据>>>"+jsonStr);
return jsonStr;
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonStr;
}</span>