【问题标题】:Send and receive json message over https通过 https 发送和接收 json 消息
【发布时间】:2015-01-29 13:01:12
【问题描述】:

我有一个 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阶段),还是需要做其他实质性修改?

【问题讨论】:

  • 你只需要把url改成https://
  • 对我来说,它适用于网址中的 https://
  • so HttpPost 自动协商密钥并选择加密算法?

标签: android json ssl https


【解决方案1】:

使用以下代码使用 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();
        }

【讨论】:

  • 我不需要将 json 发送到服务器。请求是一个简单的 POST,只有响应是 JSON 消息
【解决方案2】:

如果您从服务器收到响应,则必须尝试此操作。

static JSONObject jObj = null;
        static String json = "";
        StringBuilder builder =new StringBuilder();
        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();
         while(is.read()!=-1){
             builder.append((char)is.read());
         }

        is.close();
        json = builder.toString();
        jObj = new JSONObject(json);

【讨论】:

    猜你喜欢
    • 2019-09-28
    • 2017-05-16
    • 2015-02-03
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多