java—如何在json的头和体中执行post请求

3df52oht  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(336)

我正在使用json,希望通过用户名、正文中的密码和标题中的x-auth-app-id、x-auth-app-hash向服务器发送post请求。。
我对postmen进行了测试,它返回200(状态正常),但是当我构建源代码时,它会发生错误。
这是我的课头:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;

public class HttpRequestUtil {
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
    JSONObject jsonObject = null;
    StringBuffer buffer = new StringBuffer();
    InputStream inputStream=null;

    try {
        URL url = new URL(requestUrl);
        HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);

        httpUrlConn.setRequestProperty("x-auth-app-id", "6166611659356156223");
        httpUrlConn.setRequestProperty("x-auth-app-hash", "a44f4ea21475fa6761392ba4bc659990bee771c413b2c207490a79f9ec78c2a61234");
        httpUrlConn.setRequestProperty("Content-Type", "application/json");

        httpUrlConn.setRequestMethod(requestMethod);

        if ("POST".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        if (null != outputStr) {
            OutputStream outputStream = httpUrlConn.getOutputStream();

            outputStream.write(outputStr.getBytes("UTF-8"));
            outputStream.close();
        }

        inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        bufferedReader.close();
        inputStreamReader.close();

        inputStream.close();
        inputStream = null;
        httpUrlConn.disconnect();
      jsonObject = JSONObject.fromObject(buffer.toString());
    }

    catch (ConnectException ce) {
          ce.printStackTrace();
          System.out.println("Our server connection timed out");
    }

    catch (Exception e) {
           e.printStackTrace();
           System.out.println("https request error:{}");
    }

    finally {
        try {
            if(inputStream!=null) {
                inputStream.close();
            }
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return jsonObject;
}
}

和类主体:

import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class CallCenterController {
  public static void main(String[] args) throws JSONException {
    String sipUser = "vchi_dd";
    String sipPassword = "m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa";

    Map<String, Object> sipAccount = new HashMap<String, Object>();

    sipAccount.put("sipUser", sipUser);
    sipAccount.put("sipPassword", sipPassword);

    sipAccount = postData(sipUser, sipPassword);
    System.out.println("result: " + sipAccount);
};

public static JSONObject postData(String sipUser, String sipPassword) {
    String url="https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser="+sipUser+"&sipPassword="+sipPassword;
    return HttpRequestUtil.httpRequest(url, "POST", "");
 }
}

当我构建它时,会发生如下异常:

java.io.IOException: Server returned HTTP response code: 400 for URL: https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser=vchi_dd&sipPassword=m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa
  https request error:{}
  result: null
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.mypackage.HttpRequestUtil.httpRequest(HttpRequestUtil.java:63)
at com.mypackage.CallCenterController.postData(CallCenterController.java:45)
at com.mypackage.CallCenterController.main(CallCenterController.java:34)

如何将正确的数据发送到我的url并解决问题?

hlswsv35

hlswsv351#

如果您的java版本足够高,我会使用javahttp客户端api。这里有一个链接https://www.baeldung.com/java-9-http-client
我用过,感觉更容易维护,更清晰。
而且,看起来你发送的请求的正文是空的,即使你在问题中说你在正文中发送用户名和密码。如果你不使用Map,为什么要在Map上添加用户名和密码?
sipcount.put(“sipuser”,sipuser);
sipcount.put(“sippassword”,sippassword);

相关问题