gpt4 book ai didi

android - 通过 https 发送和接收 json 消息

转载 作者:太空宇宙 更新时间:2023-11-03 14:56:52 26 4
gpt4 key购买 nike

我有一个 android 应用程序,它在服务器上调用一些 php 脚本,并通过使用“正常”HTTP 连接接收 json 消息作为响应:

static JSONObject jObj = null;
static String json = "";

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");

}
is.close();
json = sb.toString();
jObj = new JSONObject(json);
//code for parse jObj Object

现在我需要将整个服务器转移到使用 ssl 加密数据的新服务器上。在开始服务器迁移之前,我需要知道如何修改我的 android 源代码以便通过 https 使用它。只需要用https修改脚本地址(HttpPost自动管理所有https阶段),还是需要做其他实质性的修改?

最佳答案

使用以下代码通过post方法向服务器发送json数据。

try {
HttpClient httpClient = new DefaultHttpClient();
JSONObject object = new JSONObject();
object.put("Username", "testUser@123");
object.put("Password", "testPassword@123");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Authentication", object);
jsonObject.put("RequestType", 4);
HttpPost postMethod = new HttpPost("your_url");
postMethod.setEntity(new StringEntity(jsonObject.toString()));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(postMethod);
HttpEntity entity = response.getEntity();
String response_value = EntityUtils.toString(entity).toString();
} catch (Exception e) {
e.printStackTrace();
}

关于android - 通过 https 发送和接收 json 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28215437/

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