在java中发送JSON Post HTTP请求[重复]

问题描述 投票:0回答:2

我正在尝试连接到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());







    }

}

得到以下错误

线程“main”中的异常java.lang.NoClassDefFoundError:org.apache.http.conn.ssl.DefaultHostnameVerifier中的org / apache / commons / logging / LogFactory。(DefaultHostnameVerifier.java:70)位于org.apache.http.impl。 client.HttpClientBuilder.build(HttpClientBuilder.java:944)at lonexaapicon.LonexaApiCon.main(LonexaApiCon.java:33)由java.net.URLClassLoader引起的:java.lang.ClassNotFoundException:org.apache.commons.logging.LogFactory。 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个

java json api http-post
2个回答
1
投票

你使用这种依赖吗?他们为我工作。除了代码本身,但它的另一个问题

            <!-- 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>

0
投票

将apache HttpCore版本更新到4.4.3对我有用

© www.soinside.com 2019 - 2024. All rights reserved.