У меня есть веб-страница, которая отвечает на запрос для ведения журнала с 1 (true) или 0 (false). Когда я пытаюсь вызвать петицию с другой веб-страницы результат является правильным, и это может быть 0 или 1. Но когда я называю это капелька в Android App результат всегда равен 0.Ответ на запрос HttpPost
Это мой код:
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result = "";
String sJSon = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://myURL");
//Build jsonObject
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("token", "123456789");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
jsonObject.accumulate("passw", "test");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
jsonObject.accumulate("email", "[email protected]");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Convert JSONObject to JSON to String
sJSon = jsonObject.toString();
//Encoding POST data
try {
httpPost.setEntity(new StringEntity(sJSon));
//Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
// write response to log
// receive response as inputStream
inputStream = response.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream); //THE RESULT SHOULD BE 1 AND NO 0 WHEN THE LOGGING IS OK. BUT IT IS ALWAYS 0
else
result = "Did not work!";
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
if (result == "1"){
Intent intent = new Intent(LoginActivity.this, MenuActivity.class);
startActivity(intent);
}
return null;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
Спасибо!
Вы должны использовать equals для сравнения строк. Что-то вроде 'if (" 1 ".equals (result))'. Кроме того, 'EntityUtils' как метод' toString', который принимает в качестве параметра 'Entity' и возвращает' Strin'g, представляющий сам объект. Если бы я был в вас, я предпочел бы использовать это, чем 'convertInputStreamToString' – Blackbelt
Как и предлагалось @blackbelt, вы также должны попробовать это. Вместо 'Accept' использовать' Accept-Encoding'. – User12111111