由於項目抓的緊,發現一個url傳參的問題,忙里偷閑整理了一下。
首先得說明,我是要用過另一個項目的url獲取json串解析出來給自己的接口使用,這是在java中完成。一般的情況是這樣的:
1 public static void main(String args[]){ 2 String url="http://123.56.6.112:2080/ec_app_api/article/getfirst?params={v:1}"; //通過?在后面傳參 3 StringBuilder json = new StringBuilder(); 4 try { 5 URL urlObject = new URL(url); 6 URLConnection uc = urlObject.openConnection(); 7 BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"UTF-8")); 8 String inputLine = null; 9 while ( (inputLine = in.readLine()) != null) { 10 json.append(inputLine); 11 } 12 in.close(); 13 } catch (MalformedURLException e) { 14 e.printStackTrace(); 15 } catch (IOException e) { 16 e.printStackTrace(); 17 } 18 String json1=json.toString(); 19 System.out.println(json1); 20 Map<String,Object> mapa = new HashMap<String,Object>(); //map的value必須為object 21 mapa = JSONObject.fromObject(json1); 22 System.out.println(mapa); 23 Map<String,Object> mapb = JSONObject.fromObject(mapa.get("data")); //獲取date里面的參數,這也是一個map集合 24 System.out.println(mapb); 25 String title=mapb.get("title").toString(); 26 String content=mapb.get("content").toString(); 27 String id=mapb.get("id").toString(); 28 System.out.println("@@@@@@@@@@@@@@"+title+"@@@@@@@@@@@@@@@@");
然而,今天的項目是通過postman插件里面的raw請求可以成功,而一般的form—date是不成功的。查資料后才發現raw是一種原始的字符串請求方式。因此找到相關的方法就好了;下面是請求的代碼:
public static void main(String args[]) throws Exception{ String jsonTemp="{\"method\": \"GetCourtServItemList\",\"version\": \"ljapp_v1.0.0\",\"courtId\":283}"; String method="GetCourtServItemList"; String url = "http://115.28.5.221:8080/api/GetCourtServItemList.json"; HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); StringEntity postingString = new StringEntity(jsonTemp);// jsonTemp的傳遞 post.setEntity(postingString); post.setHeader("Content-type", "application/json"); HttpResponse response = httpClient.execute(post); String content = EntityUtils.toString(response.getEntity()); System.out.println(content); }
好了,這樣請求就成功了。