2014-12-01 4 views
1

httpClient를 사용하여 웹 서비스에 android-json 요청을 보내려고합니다.JSONObject를 매개 변수로 사용하여 JSON 요청을 보내시겠습니까?

{ "ID": "ID", "방법", "PARAMS"를 "인증"{ "사용자"제가 를 "인증"되는 호출 할 있어서, 상기 요청은 다음과 같은 구조를 가지고 있어야 "안드로이드" "비밀번호": "PASSWORD", "클라이언트": "CLIENT"}, "JSONRPC": "2.0"}

필수 매개 변수 : 학교 = SCHOOLNAME는

이다 내가 시도 :

class MyAsnycTask extends AsyncTask<String, String, String>{ 

    protected String doInBackground(String... params) { 
     String apiUrl = "https://arche.webuntis.com/WebUntis/jsonrpc.do"; 
     JSONObject jsonParams = new JSONObject(); 
     JSONObject params1 = new JSONObject(); 


     HttpClient client = new DefaultHttpClient(); 

     // Prepare a request object 
     HttpPost post = new HttpPost(apiUrl); 
     post.setHeader("Content-type", "application/json"); 
     try { 
      params1.put("?school","litec"); 
      params1.put("user", "40146720133271"); 
      params1.put("password", "1234567"); 

      jsonParams.put("id", "ID"); 
      jsonParams.put("method", "authenticate"); 
      jsonParams.put("params", params1); 
      jsonParams.put("jsonrpc", "2.0"); 

      StringEntity se = new StringEntity(jsonParams.toString()); 
      post.setEntity(se); 

     } catch (JSONException e1) { 
      e1.printStackTrace(); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } 
     // Execute the request 
     try { 
      HttpResponse response = client.execute(post); 
      Log.d("log_response: ", response.getStatusLine().toString()); 

      // Get hold the response entity 
      HttpEntity entity = response.getEntity(); 

      // if the response does not enclose the entity, there is no need 
      // to worry about it 

      if(entity != null){ 
       // a simple JSON Response read 
       InputStream instream = entity.getContent(); 
       String result; 

       // convert content of response to bufferedreader 
       BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); 
       StringBuilder sb = new StringBuilder(); 

       String line = null; 
       try { 
        while ((line = reader.readLine()) != null){ 
         sb.append(line + "\n"); 
        } 
       } catch (IOException e) { 
        e.printStackTrace(); 
       }finally{ 
        try{ 
         instream.close(); 
        }catch(IOException exp){ 
         exp.printStackTrace(); 
        } 
       } 
       result = sb.toString(); 
       Log.d("Result of the Request: ", result); 
      } 


     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     return "OK"; 
    } 
    protected String doInBackground(String result) { 
     return result; 
     // TODO Auto-generated method stub 

    } 
} 

실행 후, 나는 r equest :

{ "JSONRPC": "2.0", "ID": "오류", "오류": { "메시지": "잘못된 schoolname", "코드"- 8500}} 그래서

그것은 우리 학교 이름이 틀렸다는 것을 말하고 있습니다. 내가 할 수있는 일은 매개 변수를 잘못 전달하는 것입니까?

답변

0

얼마 전에 질문을 보았지만 대답 할 수 없었습니다. 나는 또한 WebUntis API를 사용하여 작업하고 있는데, 만약 당신이 오류를 해결했는지 모르겠다. 그러나 URL에 간단한 오류가있다. API에서 언급되는 것처럼 'authenthicate'메소드의 필수 매개 변수는 ?school=SCHULNAME입니다. 코드의 URL은 'https://arche.webuntis.com/WebUntis/jsonrpc.do'이지만 필수 매개 변수 SCHULNAME은 제공되지 않습니다. 귀하의 URL은 다음과 같아야합니다 : https://arche.webuntis.com/WebUntis/jsonrpc.do?school=SCHULNAME. 어쩌면 요청 길이를 추가해야 할 수도 있습니다. 예 : authenthicate 메소드를 사용하는 경우 : {"id":"ID","method":"authenticate","params":{"user":"USR", "password":"PW", "client":"MyApp"},"jsonrpc":"2.0"} 이 경우 길이는 109입니다.이 질문이 한 달 넘은 경우에도 도움이 되었기를 바랍니다. 다른 Google 직원의 경우 : AsyncTask를 사용하지 않는 경우 true가 아닌 ok를 반환해야합니다.

편집 :

코드는 (내가 아직 테스트하지 않은, 나는 그것이 작동하는 희망)과 같습니다

:

class MyAsnycTask extends AsyncTask<String, String, String>{ 

protected String doInBackground(String... params) { 
    String apiUrl = "https://arche.webuntis.com/WebUntis/jsonrpc.do?school=SCHULNAME"; //Changes here 
    JSONObject jsonParams = new JSONObject(); 
    JSONObject params1 = new JSONObject(); 


    HttpClient client = new DefaultHttpClient(); 

    // Prepare a request object 
    HttpPost post = new HttpPost(apiUrl); 
    post.setHeader("Content-type", "application/json"); 
    try { 
     params1.put("user", "40146720133271"); 
     params1.put("password", "1234567"); 
     params1.put("client", "seriouslysAndroidApp"); //You can change the name 

     jsonParams.put("id", "ID"); 
     jsonParams.put("method", "authenticate"); 
     jsonParams.put("params", params1); 
     jsonParams.put("jsonrpc", "2.0"); 

     StringEntity se = new StringEntity(jsonParams.toString()); 
     post.setHeader("Content-length",""+se.getContentLength()); //header has to be set after jsonparams are complete 
     post.setEntity(se); 

    } catch (JSONException e1) { 
     e1.printStackTrace(); 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } 
    // Execute the request 
    try { 
     HttpResponse response = client.execute(post); 
     Log.d("log_response: ", response.getStatusLine().toString()); 

     // Get hold the response entity 
     HttpEntity entity = response.getEntity(); 

     // if the response does not enclose the entity, there is no need 
     // to worry about it 

     if(entity != null){ 
      // a simple JSON Response read 
      InputStream instream = entity.getContent(); 
      String result; 

      // convert content of response to bufferedreader 
      BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); 
      StringBuilder sb = new StringBuilder(); 

      String line = null; 
      try { 
       while ((line = reader.readLine()) != null){ 
        sb.append(line + "\n"); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      }finally{ 
       try{ 
        instream.close(); 
       }catch(IOException exp){ 
        exp.printStackTrace(); 
       } 
      } 
      result = sb.toString(); 
      Log.d("Result of the Request: ", result); 
     } 


    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    return "OK"; 
} 
protected String doInBackground(String result) { 
    return result; 
    // TODO Auto-generated method stub 

} 
+0

덕분에 많이, 내가 지금 대답을 읽을 수 있지만 내가 응용 프로그램을 발견 webuntis와 함께 작동하고 내가 언급 한 것처럼 URL 끝 부분에 SCHOOL 매개 변수를 넣어야한다는 것을 알게되었습니다. – seriously

+0

그래, 난이 애플 리케이션을 너무 찾았지만, 실마리가 나에게 증언이 없다면, 내 목적에 쓸모가 없다. api로 작업 할 때 행운을 빈다 :-) – kernelmaster

+0

나는 또한 그것에 대한 작업에 문제가있어, 나는 이것을 위해 자신 만의 Java API를 만들었는데, 여기에는 webuntis로 뭔가 작업하는 https://github.com/Luftbaum/WebUntisAPI – Luftbaum

관련 문제