尝试将C#HTTP请求转换为Android

时间:2019-03-19 10:54:38

标签: java c# android android-volley

我从azure ml studio获得了此代码段,以访问训练有素的ML模型,但是有一个问题,我希望可以通过Android应用程序对其进行访问。但是该代码段是C#和python的唯一Android。

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace CallRequestResponseService

{

public class ScoreData
{
    public Dictionary<string, string> FeatureVector { get; set; }
    public Dictionary<string, string> GlobalParameters { get; set; }
}

    public class ScoreRequest
    {
        public string Id { get; set; }
        public ScoreData Instance { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            InvokeRequestResponseService().Wait();
        }

        static async Task InvokeRequestResponseService()
        {
            using (var client = new HttpClient())
            {
                ScoreData scoreData = new ScoreData()
                {
                    FeatureVector = new Dictionary<string, string>() {
                        { "49", "0" },
                        { "1", "0" },
                        { "162", "0" },
                        { "54", "0" },
                        { "78", "0" },
                        { "0", "0" },
                        { "1 (3)", "0" },
                   },
                    GlobalParameters = new Dictionary<string, string>() {
                  }
                };

                ScoreRequest scoreRequest = new ScoreRequest()
                {
                    Id = "score00001",
                    Instance = scoreData
                }; 
                const string apiKey = "abc123"; // Replace this with the API key for the web service
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", apiKey);

                client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/eda583b8ec244b9092bdce09c6884046/services/19f80ec6f14c42deb41649bbb4b7b591/score");

                // WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application.
                // One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context.
                // For instance, replace code such as:
                //      result = await DoSomeTask()
                // with the following:
                //      result = await DoSomeTask().ConfigureAwait(false)


                HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Result: {0}", result);
                }
                else
                {
                    Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));

                    // Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
                    Console.WriteLine(response.Headers.ToString());

                    string responseContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseContent);
                }
            }
        }
    }
}

我已经尽我最大的努力在android中实现了它,我使用了volley,但坚持将正文放在发布请求中。预先感谢。

    package com.example.user.volleyapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    //Declare a private RequestQueue variable
    private RequestQueue requestQueue;
    private String api_key = "kXobBe1KsjND/AdkE6GLaMlSyWUXQYMNrMnNSUgfiCOer+7enQ2Em4wahR/3/5mAffF3IATzoKfOXrxKXtWDlQ==";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //URL of the request we are sending
        String url = "https://ussouthcentral.services.azureml.net/workspaces/eda583b8ec244b9092bdce09c6884046/services/19f80ec6f14c42deb41649bbb4b7b591/score";

        ScoreData scoreData = new ScoreData();
        //{FeatureVector = ; GlobalParameters = new HashMap<String, String>() { }};
        HashMap<String, String> M = new HashMap<String, String>();
        M.put("49", "0"); M.put("1", "0"); M.put("162", "0");M.put("54","0"); 
        scoreData.setFeatureVector(M);
        HashMap<String, String> G = new HashMap<String, String>();
        scoreData.setGlobalParameters(G);

        ScoreRequest SR = new ScoreRequest();
        SR.setId("score00001");
        SR.setInstance(scoreData);

        Gson gson = new Gson();
        String json = gson.toJson(SR);




        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
                url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("response", response.toString()
                        );
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        //Failure Callback
                    }
                })

        {

            /** Passing some request headers* */
            @Override
            public Map getHeaders() throws AuthFailureError {
                HashMap headers = new HashMap();
                headers.put("Content-Type","application/json");
                headers.put("Authorization","Bearer "+api_key);
                return headers;
            }
        };

// Adding the request to the queue along with a unique string tag
MyApplication.getInstance().addToRequestQueue(jsonObjReq, "headerRequest");

    }

}
class ScoreData
{
    private Map<String, String> FeatureVector;
    public final Map<String, String> getFeatureVector()
    {
        return FeatureVector;
    }
    public final void setFeatureVector(Map<String, String> value)
    {
        FeatureVector = value;
    }
    private Map<String, String> GlobalParameters;
    public final Map<String, String> getGlobalParameters()
    {
        return GlobalParameters;
    }
    public final void setGlobalParameters(Map<String, String> value)
    {
        GlobalParameters = value;
    }
}
class ScoreRequest
{
    private String Id;
    public final String getId()
    {
        return Id;
    }
    public final void setId(String value)
    {
        Id = value;
    }
    private ScoreData Instance;
    public final ScoreData getInstance()
    {
        return Instance;
    }
    public final void setInstance(ScoreData value)
    {
        Instance = value;
    }
}

0 个答案:

没有答案