我有一个安卓应用程序,它在服务器上调用一些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 处理加密数据的新服务器上传输整个服务器。在开始服务器迁移之前,我需要知道 ho 来修改我的 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();
}
如果您从服务器获得响应,则必须尝试此操作。
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);