gpt4 book ai didi

android - 如何调用 JSON 网络服务?

转载 作者:行者123 更新时间:2023-11-29 01:38:58 27 4
gpt4 key购买 nike

我正在尝试调用此网络服务,但它的响应为空

<script type="text/javascript">
jQuery(document).ready(function(){
var user = {nick :"rajesh", password:"123456", device_id:"123456677"};
jQuery.ajax({
type: "post",
data :JSON.stringify(user),
url: "http://localhost:81/sazpin/user/users/index.json",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
console.log(data);
}
});
});
</script>

我的 httppost 客户端是

HttpClient httpClient = new DefaultHttpClient();

// post header
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

请有人帮助我如何调用此网络服务并获得响应?

最佳答案

试试这段代码。首先创建您的 AsyncTask。

public class ResquestJSON extends AsyncTask<String, Void, String>{
JSONObject jsonObject = new JSONObject();
String response;

protected String doInBackground(String... params){
HttpPost httpPost = new HttpPost("http://192.168.10.101:8090/download");//your webservice url here
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
try {
jsonObject.put("firstParam", params[0]);
jsonObject.put("secondParam", params[1]);

StringEntity se = new StringEntity(jsonObject.toString());
httpPost.addHeader("Content_Type", "application/json");
httpPost.setEntity(se);
HttpResponse httpResponse = httpClient.execute(httpPost, httpContext);

HttpEntity entity = httpResponse.getEntity();

if (entity!=null){
response = EntityUtils.toString(entity);
entity.consumeContent();
httpClient.getConnectionManager().shutdown();
}
} catch (JSONException|IOException|IllegalArgumentException e) {
return UtilityConstants.ERROR;
}
return response;
}

现在像这样从您的 Activity 中调用此 AsyncTask 方法。

String response = new ResquestJSON().execute(firstParam, secondParam).get();
JSONObject obj = new JSONObject(response);
String nick = obj.getString("nick");
String password = obj.getString("password");
String deviceId = obj.getString("deviceId");

希望对你有帮助。

关于android - 如何调用 JSON 网络服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26015752/

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