java後臺模擬傳送post請求,get也請用此種方式避免編碼問題
阿新 • • 發佈:2019-02-17
public static String geturl1(String geturl,String content) throws Exception {
//請求的webservice的url
URL url = new URL(geturl);
//建立http連結
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//設定請求的方法型別
httpURLConnection.setRequestMethod("POST" );
//設定請求的內容型別
httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
//設定傳送資料
httpURLConnection.setDoOutput(true);
//設定接受資料
httpURLConnection.setDoInput(true);
//傳送資料,使用輸出流
OutputStream outputStream = httpURLConnection.getOutputStream();
//傳送的soap協議的資料
// String requestXmlString = requestXml("北京");
//String content = "user_id="+ URLEncoder.encode("13846", "gbk");
//傳送資料
outputStream.write(content.getBytes());
//接收資料
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null){
buffer.append(line);
}
String str = buffer.toString();
return str;
}
字串轉為json物件並獲取其中屬性
String addrJson = GnthkUtil.geturl1();
JSONObject jobjectaddr = JSON.parseObject(addrJson);
String addr=jobjectaddr.getJSONObject("result").getString("formatted_address");
如果獲得的jsonobject的裡面是陣列
則:
@RequestMapping("/toProduct")
public String toProduct() {
try {
String addrJson = GnthkUtil.geturl("http://xxxxxxxxx", "");
JSONObject jsonObject = JSON.parseObject(addrJson);
JSONArray array = jsonObject.getJSONArray("result");
String string = jsonObject.getJSONArray("result").toJSONString();
for(int i=0;i<array.size();i++){
JSONObject job = array.getJSONObject(i); // 遍歷 jsonarray 陣列,把每一個物件轉成 json 物件
System.out.println(job.get("pdtname"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}