Я пытаюсь создать приложение для интерфейса Asterisk, настройка конфигурации была выполнена правильно, поскольку я дважды проверил ее.Как использовать Cookies в HttpURLConnection для ANDROID?
Похоже, причина, по которой я не могу получить доступ к файлам конфигурации с сервера Asterisk, связан с соединением. Мне нужно использовать cookie для подключения к тому же экземпляру сеанса входа в систему.
Но до сих пор я не могу использовать Cookie. Нужно немного помочь.
Я должен войти в систему, нажав button1 (bt1) и получить конфигурационный файл, нажав кнопку2 (btn2).
public class AsteriskInterface extends Activity {
private static final String TAG = " AsteriskInterface";
EditText ed1;
Button bt1,bt2;
static String url ="http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
static String logincmd ="http://192.168.8.2:8088/asterisk/rawman?action=login&username=admin&secret=admin123";
static String getfilecmd = "http://192.168.8.2:8088/asterisk/rawman?action=getconfig&filename=sip.conf";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed1 = (EditText) this.findViewById(R.id.editText);
bt1 = (Button) this.findViewById(R.id.submit);
bt2 = (Button) this.findViewById(R.id.config);
final WebView myWebView = (WebView) findViewById(R.id.webView);
bt1.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
try{
new Execute().execute(logincmd);
} catch(Exception e) {
Log.v("Exception execute", "Exception:"+e.getMessage());
}
}
});
bt2.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
try{
new Execute().execute(getfilecmd);
} catch(Exception e) {
Log.v("Exception execute", "Exception:"+e.getMessage());
}
//myWebView.loadUrl(cmd2);
}
});
}
public static void Response(String result) {
Log.e(TAG,result);
}
}
class Execute extends AsyncTask<String, Integer, String> {
List<String> cookies = null;
protected String doInBackground(String... searchKey) {
String cmd = searchKey[0];
try {
return action2(cmd);
} catch(Exception e) {
Log.v("Exception execute do back ground", "Exception:"+e.getMessage());
return "";
}
}
protected void onPostExecute(String result) {
try {
AsteriskInterface.Response(result);
} catch(Exception e) {
Log.v("Exception excecute onPost Execute",
"Exception:"+e.getMessage());
}
}
private String action2(String uRL) throws MalformedURLException, IOException {
StringBuilder response = new StringBuilder();
Log.v("Execute","execute url:"+uRL);
URL url = new URL(uRL);
HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
DataOutputStream out;
DataInputStream in;
if(cookies==null){
httpconn.getHeaderField("Set-Cookie");
}
if(cookies!=null){
for(String cookie : cookies){
httpconn.setRequestProperty("Cookie", cookie);
}
}
httpconn.setDoOutput(true);
String post = "mobile_app="+URLEncoder.encode("1","UTF-8");
out = new DataOutputStream(httpconn.getOutputStream());
out.writeBytes(post);
out.flush();
out.close();
in = new DataInputStream(httpconn.getInputStream());
String line = "";
String data = "";
while((line=in.readLine())!=null){
data+=line;
}
if(httpconn.getResponseCode()==HttpURLConnection.HTTP_OK) {
BufferedReader input = new BufferedReader(
new InputStreamReader(httpconn.getInputStream()),
8192);
String strLine = null;
while ((strLine = input.readLine()) != null) {
response.append(strLine);
}
input.close();
}
return response.toString();
}
}
Я могу понять, что подключаюсь к предыдущей сессии входа. Но теперь, как выпустить новую команду?
03-28 10: 02: 15,861: V/Execute (4261): выполнить URL: http://192.168.8.x:8088/asterisk/rawman?action=login&username=admin&secret=admin123 03-28 10: 02: 18,871: V/Исключение выполнения делать обратно землю (4261): Исключение: Уже подключено 03-28 10: 02: 23.651: V/Execute (4261): выполнить URL: http://192.168.8.x:8088/asterisk/rawman?action=getconfig&filename=sip.conf 03-28 10: 02: 26.691: V/Exception execute do back ground (4261): Исключение: уже подключено 03-28 10: 02: 26,721 D/dalvikvm (4261): GC_CONCURRENT освободил 226K, 8% бесплатно 7430K/8007K, остановился 24ms + 3ms, всего 61ms
что sCookie ..? –
sCookie является статическим? –
@ Harsh Его строка – user2119228