2012-04-13 6 views
4

왜이 오류가 오전 : java.lang.IllegalArgumentException를 :이 소비자 유형의 요청을 예상 org.apache.http.HttpRequest왜 java.lang.IllegalArgumentException 오류가 발생합니까?

CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer (CONSUMER_KEY,CONSUMER_SECRET); 
      consumer.setTokenWithSecret(oaut_token, tokenSecret); 

URL url = new URL(targetURL); 
request = (HttpURLConnection) url.openConnection(); 

// sign the request 
consumer.sign(request); 
// send the request 
request.connect(); 

편집 : 그것은 관련이 없습니다로 그냥 허용 대답을 업데이트 더 이상. 푯말 문서가 조금 구식이며 HttpURLConnection의 버그로 인해 Android에서 CommonsHttpOAuthConsumer를 사용하도록 제안합니다. 이것들이 수정되어 안드로이드가 아파치 HTTP를 제거 했으므로 푯말을 다루는 올바른 방법은 이제 DefaultOAuthConsumer을 통해 이루어진다. 메소드가 인수 유형을 예상 할 때

DefaultOAuthConsumer consumer = new DefaultOAuthConsumer (CONSUMER_KEY,CONSUMER_SECRET); 
      consumer.setTokenWithSecret(oaut_token, tokenSecret); 

URL url = new URL(targetURL); 
request = (HttpURLConnection) url.openConnection(); 

// sign the request 

consumer.sign(request); 
+0

에 가기로 고객을 수 있다고? – daveb

+0

내가 제공 한 답변 (한 번 아래로)을 살펴보고 같은 문제가 발생했을 때 나와 설명 된 솔루션이 나에게 도움이되었습니다. – Idistic

답변

5

푯말은 실제로 최신이 아니거나 완료되지 않았거나 특히 유용한 순서의 자습서를 지나면 안드로이드, 롤에서 사용하기 쉽습니다.

어쨌든 여기에 네이티브 안드로이드 대신 아파치 http를 사용하는 한 가지 방법이 있습니다. 간결성을 위해보기에는 약간 엉망이지만 꼭 실행시켜야합니다.

코드를 조금만 수정하면 호출간에 일관된 HttpClient를 만들고 싶지만 그저 모든 것을 인라인했다. 또한 토큰을 deserialize하고 있다는 사실을 알았 기 때문에 실제 OAuth 플로우가 작동한다고 가정합니다.

행운을 빈다.

CommonsHttpOAuthConsumer consumer = null; 
    consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,CONSUMER_SECRET); 
    consumer.setTokenWithSecret(oaut_token, tokenSecret); 

    // Use the apache method instead - probably should make this part persistent until 
    // you are done issuing API calls  
    HttpParams parameters = new BasicHttpParams(); 
    HttpProtocolParams.setVersion(parameters, HttpVersion.HTTP_1_1); 
    HttpProtocolParams.setContentCharset(parameters, HTTP.DEFAULT_CONTENT_CHARSET); 
    HttpProtocolParams.setUseExpectContinue(parameters, false); 
    HttpConnectionParams.setTcpNoDelay(parameters, true); 
    HttpConnectionParams.setSocketBufferSize(parameters, 8192); 

    HttpClient httpClient = new DefaultHttpClient(); 

    SchemeRegistry schReg = new SchemeRegistry(); 
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
    ClientConnectionManager tsccm = new ThreadSafeClientConnManager(parameters, schReg); 

    httpClient = new DefaultHttpClient(tsccm, parameters); 

    HttpGet get = new HttpGet(targetURL); 

    // sign the request 
    consumer.sign(get); 

    // send the request & get the response (probably a json object, but whatever) 
    String response = httpClient.execute(get, new BasicResponseHandler()); 

    // shutdown the connection manager - last bit of the apache code 
    httpClient.getConnectionManager().shutdown(); 

    //Do whatever you want with the returned info 
    JSONObject jsonObject = new JSONObject(response); 

+0

서명을 생성하는 푯말 방법이 내장되어 있습니까? – Fabii

+0

@Fabii 당신이 묻고있는 것을 정확히 이해하지 못했는지, 서명 방법이 당신을 위해 모든 것을 처리하거나 반자동 도우미 메서드를 사용하여 서명을 직접 구성하여 수정할 수 있는지 찾고 있습니까? (논스, 토큰 등과 같은 것들) – Idistic

5

그것은 당신이 request 것을 게시 된 코드에서 명백해야한다는

request = (HttpURLConnection) url.openConnection(); 
consumer.sign(request); 
+0

그래서이 사이트가 부정확하다고 말하는 것입니까? : http : //code.google.com/p/oauth-signpost/wiki/GettingStarted – Fabii

+0

Apache Commons HTTP를 사용하고 있습니까? Android 용으로이 책을 쓰고 있습니까? 이 기사에는 많은주의 사항이 있습니다. ** 다른 HTTP 요청 유형에 대한 요청에 서명해야하는 경우 SupportedHttpLibraries의 예제를 참조하십시오. ** –

+0

@Fabii - 여기에있는 자습서에는 Apache HTTP 사용이 표시되지 않습니다. android handlers의 버그로 인해 Android 앱에 필요합니다. 트래비스는 올바른 방향으로 당신을 지적했습니다. 안드로이드 및 푯말과 함께 작동하는 무언가에 대한 아래의 내 대답을보세요 – Idistic

1

예외 예외 : IllegalArgumentException가 발생 ... 유형 HttpRequest이 아닌 다른 유형을 수신합니다. 이 경우
는 방법은 sign하고 인수는 request : HTTPRequest 유형을받을하기 위해 기다리고

consumer.sign(request); 

과는 다른 유형을 잡입니다.

0
public class BlockTicketPostOauth extends AsyncTask<String, Void, Integer> { 
    ProgressDialog pd; 
    String response; 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pd=new ProgressDialog(BusPassengerInfo.this); 
     pd.setMessage("wait continue to payment...."); 
     pd.show(); 

    } 

    @Override 
    protected Integer doInBackground(String... params) { 
     InputStream inputStream = null; 
     String ul ="http://api.seatseller.travel/blockTicket"; 

     String JSONPayload=params[0]; 
     Integer result = 0; 
     try { 

      OAuthConsumer consumer = new CommonsHttpOAuthConsumer(YOUR CONSUMER KEY,YOUR CONSSUMER SECRETE); consumer.setTokenWithSecret(null, null); 

      /* create Apache HttpClient */ 
      HttpClient httpclient = new DefaultHttpClient(); 

      /* Httppost Method */ 
      HttpPost httppost = new HttpPost(ul); 

      // sign the request 
      consumer.sign(httppost); 

      // send json string to the server 
      StringEntity paras =new StringEntity(JSONPayload); 

      //seting the type of input data type 
      paras.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 

      httppost.setEntity(paras); 

      HttpResponse httpResponse= httpclient.execute(httppost); 

      int statusCode = httpResponse.getStatusLine().getStatusCode(); 

      Log.i("response json:","status code is:"+statusCode); 
      Log.i("response json:","status message?:"+httpResponse.getStatusLine().toString()); 

      /* 200 represents HTTP OK */ 
      if (statusCode == 200) { 
       /* receive response as inputStream */ 
       inputStream = httpResponse.getEntity().getContent(); 
       response = convertInputStreamToString(inputStream); 

       Log.i("response json:","json response?:"+response); 

       Log.i("response block ticket :","status block key:"+response); 

       result = 1; // Successful 
      } else{ 
       result = 0; //"Failed to fetch data!"; 
      } 
     } catch (Exception e) { 
      Log.d("response error", e.getLocalizedMessage()); 
     } 
     return result; //"Failed to fetch data!"; 
    } 

    @Override 
    protected void onPostExecute(Integer result) { 

     if(pd.isShowing()){ 
      pd.dismiss(); 
     } 
     /* Download complete. Lets update UI */ 
     if(result == 1){ 

      Toast.makeText(BusPassengerInfo.this,"response is reult suceess:"+response,Toast.LENGTH_SHORT).show(); 

// 요청이 생성되는 방법 지불 게이트 방식

 }else{ 
      Log.e("response", "Failed to fetch data!"); 
      Toast.makeText(BusPassengerInfo.this,"response is reult fail",Toast.LENGTH_SHORT).show(); 
     } 

    } 
}