如何为Android java编写/转换CURL

t0ybt7op  于 2022-11-13  发布在  Android
关注(0)|答案(1)|浏览(131)

我正在尝试实现MOT历史API https://dvsa.github.io/mot-history-api-documentation/,他们给予了一个使用CURL的示例,在使用在线CURL工具时,该示例与提供的API密钥成功配合使用。
我正在尝试在Android中实现这一点,并意识到我必须使用类似HttpPost的东西,而不是CURL,这是我的代码:

//Tried with full URL and by adding the registration as a header.
    //HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests?registration=" + reg_selected);
     HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests");

     httpPost.addHeader("Content-Type", "application/json");
     httpPost.addHeader("Accept", "application/json+v6");
     httpPost.addHeader("x-api-key", "abcdefgh123456");
     httpPost.addHeader("registration", reg_selected);

     StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
     httpPost.setEntity(entity);
     HttpClient client = new DefaultHttpClient();

     try {
          HttpResponse response = client.execute(httpPost);

          if (response.getStatusLine().getStatusCode() == 200) {

               InputStream inputStream = response.getEntity().getContent();
               bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
               String readLine = bufferedReader.readLine();

               String jsonStr = readLine;
               JSONObject myJsonObj = new JSONObject(jsonStr);

               
          }else if (response.getStatusLine().getStatusCode() == 400){
                 //Bad Request  Invalid data in the request. Check your URL and parameters
                 error_text = "Bad Request";
          }else if (response.getStatusLine().getStatusCode() == 403){
                //Unauthorised – The x-api-key is missing or invalid in the header
                error_text = "Authentication error"; //<<<< FAILS HERE 403
          }

response.getStatusLine().getStatusCode()returns ·“403 -未授权-头部中缺少x-api-key或x-api-key无效”。然而,我使用的x-api-key在在线CURL测试中正常工作,因此实际的密钥是正确的,但我将其添加到我的Android代码请求中的方式必须是无效或类似的。
有谁能说明一下将CURL转换为Android java的正确方法,这样服务器就不会返回403?
谢谢

6jjcrrmo

6jjcrrmo1#

使用Jsoup很容易做到:

// CREATE CONNECTION
    Connection conn=Jsoup.connect("URL_GOES_HERE");
    
    // ADD POST/FORM DATA
    conn.data("KEY", "VALUE");
    
    // ADD HEADERS HERE
    conn.header("KEY", "VALUE");
    
    // SET METHOD AS POST 
    conn.method(Connection.Method.POST);
    
    // ACCEPT RESPONDING CONTENT TYPE
    conn.ignoreContentType(true);
    
    try
    {
        // GET RESPONSE
        String response = conn.execute().body();
        
        // USE RESPONSE HERE
        // CREATE JSON OBJECT OR ANYTHING...
    } catch(HttpStatusException e)
    {
        int status = e.getStatusCode();
        // HANDLE HTTP ERROR HERE
    } catch (IOException e)
    {
        // HANDLE IO ERRORS HERE
    }

***附言:*我猜你是搞混了HeaderPost Data。密钥等(凭据)必须用作Post Data,内容类型等必须用作Header

相关问题