gpt4 book ai didi

java - 如何从http请求中获取json响应?

转载 作者:行者123 更新时间:2023-12-01 22:45:52 26 4
gpt4 key购买 nike

当尝试从我的 api 检索响应 json 时,我只能获取一个字符串值,但无法将其转换为 jsonobject 来使用。

应以 json 格式响应 {"result":"success","client[id]":"1"}

但我只能检索字符串“result=success,client[id]=1”

public void createWHMCSUser(final String emailID, final String random, final String uid) {

Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
String e = URLEncoder.encode(emailID, "utf-8");
String r = URLEncoder.encode(random, "utf-8");
URL url = new URL("http://create.user.com/includes/api.php?action=AddClient&username=abc123&password=abc123&accesskey=abc123&firstname=User&lastname=Name&email=" + e +"&address1=na&city=na&state=na&poscode=00000&country=US&phonenumber=0000000000&password2=" + r + "&reponsetype=json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept","application/json");
conn.setDoOutput(true);
conn.setDoInput(true);



Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG", conn.getResponseMessage());

if(conn.getResponseCode() == 200){
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String readAPIResponse = " ";
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = in.readLine()) != null){
jsonString.append(readAPIResponse);

JSONObject obj = new JSONObject(jsonString.toString());
int aJsonString = obj.getInt("Client[id]");
SetClientID(uid,aJsonString);



}

in.close();


}

conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}

}
});

thread.start();

}

最佳答案

这样使用起来更方便快捷有关更多示例和构建库,请检查以下内容: enter link description here

 AndroidNetworking.get("URL")
.setTag("test")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
// handle your response here

}
@Override
public void onError(ANError error) {
// handle error
}
});

关于java - 如何从http请求中获取json响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58473858/

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