Java和OkHTTP

Java和OkHTTP,java,json,api,okhttp,Java,Json,Api,Okhttp,所以我对JSON的获取、拥有和使用一般来说都是非常陌生的。有人能告诉我他们是否发现我的代码有问题吗?我试图使用政府的NPI查找将医生信息返回到JSON对象中 以下是源代码: package API_Playground; import okhttp3.*; import java.io.IOException; public class Main { // one instance, reuse private final OkHttpClient httpClient

所以我对JSON的获取、拥有和使用一般来说都是非常陌生的。有人能告诉我他们是否发现我的代码有问题吗?我试图使用政府的NPI查找将医生信息返回到JSON对象中

以下是源代码:

package API_Playground;

import okhttp3.*;

import java.io.IOException;

public class Main {

    // one instance, reuse
    private final OkHttpClient httpClient = new OkHttpClient();

    public static void main(String[] args) throws Exception {

        Main obj = new Main();

        System.out.println("Testing 1 - Send Http GET request");
        obj.sendGet();

        System.out.println("Testing 2 - Send Http POST request");
        obj.sendPost();

    }

    private void sendGet() throws Exception {

        Request request = new Request.Builder()
                .url("https://npiregistry.cms.hhs.gov/api/?version=2.1")
                .addHeader("first_name", "larry")
                .addHeader("last_name", "mabine")
                .addHeader("state", "GA")
                .build();

        try (Response response = httpClient.newCall(request).execute()) {

            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // Get response body
            System.out.println(response.body().string());
        }

    }

    private void sendPost() throws Exception {

        // form parameters
        RequestBody formBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("first_name", "john")
                .addFormDataPart("last_name", "smith")
                .addFormDataPart("state", "GA")
                .build();

        Request request = new Request.Builder()
                .url("https://npiregistry.cms.hhs.gov/api?")
                .post(formBody)
                .addHeader("version", "2.0")
                .build();

        System.out.println(request.toString());

        try (Response response = httpClient.newCall(request).execute()) {

            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // Get response body
            System.out.println(response.body().string());
        }

    }

}
NPI API信息:

我收到的错误:

{"Errors":
[
    {
        "description": "Unsupported Version",
        "field": "version",
        "number": "17"
    }
]

我认为这与
json
okhttp
无关,错误信息非常清楚。我不熟悉NPPES API,但您似乎使用错误的参数调用了此API,用于
version
。如果我修改请求url以包含该版本,现在我会得到错误
{“Errors”:[{“field”:“generic”,“number”:“04”,“description”:“未提供有效的搜索条件”}
您从哪里得到响应的
sendGet()
sendPost()
?看起来您正试图将请求参数作为头传递,您可以引用此代码。