gpt4 book ai didi

java - 在java中发送JSON Post HTTP请求

转载 作者:行者123 更新时间:2023-12-02 11:34:32 24 4
gpt4 key购买 nike

我正在尝试连接到 API 以获取 json 格式的一些信息。我需要通过 json 编码的授权详细信息请求 API。请求方式为Post。但我收到错误。我需要获取 json 对象中的响应。我正在使用 apache HttpClient 和 apache HttpCore,对于 Json 解析,我使用 json-simple-1.1.1。请帮我。因为我是一名 Java 开发新手。

这是我的代码

public class LonexaApiCon {

/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
String postUrl = "http://myUrl.com/api/get-schedule-data";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(postUrl);

String access_token= "myaccesstoken";
String client_id= "myclientId";
String client_secret= "myClientSecret";
String username= "myuserName";
String password= "myPassword";
String token_type="myTokenType";


post.setHeader("authorization", (token_type.substring(0, 1).toUpperCase() + token_type.substring(1))+" "+access_token);
post.setHeader("Content-type", "application/json");


JSONObject json = new JSONObject();

json.put("grant_type","password");
json.put("client_id",client_id);
json.put("client_secret",client_secret);
json.put("username",username);
json.put("password",password);
json.put("token_type",token_type);
json.put("access_token",access_token);
json.put("transport_id","72");

post.setEntity((HttpEntity) json);
HttpResponse response = httpClient.execute(post);

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







}

}

出现以下错误

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at org.apache.http.conn.ssl.DefaultHostnameVerifier.(DefaultHostnameVerifier.java:70) at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:944) at lonexaapicon.LonexaApiCon.main(LonexaApiCon.java:33) Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 3 more

最佳答案

你正在使用这个依赖项吗?他们为我工作。除了代码本身之外,这是另一个问题

            <!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.4</version>
</dependency>

关于java - 在java中发送JSON Post HTTP请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49049487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com