2016-05-10 18 views
0

.NETで書かれたWeb APIサービスは1つあります。 サービスは、ヘッダーからトークンを読み込み、本文にデータを読み込みます。 。。.NET Web APIを呼び出す方法Androidでの投稿サービス

私は(それは、体内のヘッダとJSONデータにトークン文字列を渡す必要があり、このサーバーを呼び出すAndroidのコードを見てコードを共有してください午前

答えて

0

このAsyncTaskクラスを試してみてください。

public class GetEvents extends AsyncTask<Integer,Void,String> { 



    @Override 
    protected String doInBackground(Integer... TripId) { 
     return POSTJson(URLs.API_URL); 
    } 


    protected void onPostExecute(String result) { 
       //code after execution 
    } 

    protected void onPreExecute() { 
     super.onPreExecute(); 

    } 

    public String POSTJson(String url) { 

     UserToken = "YourToken"; 
     String json; 
     URL obj; 
     try { 
      obj = new URL(url); 
      HttpURLConnection con; 
      con = (HttpURLConnection) obj.openConnection(); 
      json = DATAtoJSON(TripId).toString(); 

//Requset headers 
      con.setRequestMethod("POST"); 
      con.setRequestProperty("Accept", "application/json"); 
      con.setRequestProperty("Content-type", "application/json"); 
      con.setRequestProperty("Token", UserToken); 


    // Send post request 
      con.setDoOutput(true); 
      DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
//request parameters 
      wr.writeBytes(json); 
      wr.flush(); 
      wr.close(); 
//receive data from request 
      in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
      response = new StringBuffer(); 
      while ((inputLine = in.readLine()) != null) { 
       response.append(inputLine); 
      } 
      in.close(); 


     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (ProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public JSONObject DATAtoJSON(int TripId) { 
     //API corresponding keys 
     String TripId_Key = History_Json_Attribute.TripId; 
     JSONObject jsonObject = new JSONObject(); 
     try { 
      jsonObject.accumulate(TripId_Key,TripId); 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return jsonObject; 
    } 
} 

このコードが送信TripIdのあるjsonオブジェクトとAPIのURL「token」ヘッダー jsonの名前がパラメータとヘッダーの名前と一致することを確認してください。そうでない場合はエラーが発生します

関連する問題