I want to read all cookies from the server but I get the following error:
java.lang.IllegalStateException: Connection already established
How can I read the cookies before connecting? I tried putting the cookie read code before defining the connection but It does not work until I define the connection which establishes the connection which prevents me from reading cookies...
Any help please?
Here's my code:
package com.example.read;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
List<String> cookies = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(l);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
View.OnClickListener l = new View.OnClickListener() {
public void onClick(View v) {
EditText edt = (EditText)findViewById(R.id.editText1);
if(!edt.getText().toString().equals("")){
readData(edt.getText().toString());
}
}
};
void readData(String text){
URL url;
HttpURLConnection conn;
DataOutputStream out;
DataInputStream in;
try{
url = new URL("http://"+text);
conn = (HttpURLConnection)url.openConnection();
if(cookies==null){
conn.getHeaderField("Set-Cookie");
}
if(cookies!=null){
for(String cookie : cookies){
conn.setRequestProperty("Cookie", cookie);
}
}
conn.setDoOutput(true);
String post = "mobile_app="+URLEncoder.encode("1","UTF-8");
out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(post);
out.flush();
out.close();
in = new DataInputStream(conn.getInputStream());
String line = "";
String data = "";
while((line=in.readLine())!=null){
data+=line;
}
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(data);
} catch(Exception e){
System.out.println(e);
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(e.toString());
}
}
}
Your question sounds a bit strange. As a client you set the cookies before establishing the connection - if you know them. The Set-Cookie header, the server returns, can only be read as soon as the answer of the server has been returned. Then of course it's to late to set any client-cookies :-)
In other words: You simply cannot read cookies from the server before you send the request.
The server sends "Set-Cookie" headers, and afterwards clients send these cookies with every following request. So you can set your "Cookie" headers only from the second request onwards.
Related
I'am following this tutorial for calling a web service in android & it works great, http://androidexample.com/Restful_Webservice_Call_And_Get_And_Parse_JSON_Data-_Android_Example/index.php?view=article_discription&aid=101
yet when i try to call another webservice using this code, just replacing the serverURL, the app gets blocked in th pre-execute(), can anyone tell me what else should I change ? I thought there was a common code for all web services ?
mainActivity.java
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button GetData = (Button) findViewById(R.id.GetServerData);
GetData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WebServer Request URL
String serverURL = "http://androidexample.com/media/webservice/JsonReturn.php";
// String serverURL = "http://hmkcode.appspot.com/rest/controller/get.json";
// String serverURL="http://gdata.youtube.com/feeds/api/videos?q=Android&v=2&max-results=20&alt=jsonc&hl=en";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
}
);
}
class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView uiUpdate = (TextView) findViewById(R.id.output);
TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server *********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
uiUpdate.setText("Output : " + Error);
} else {
// Show Response Json On Screen (activity)
uiUpdate.setText(Content);
//String OutputData = MainActivity.parse(Content);
//Show Parsed Output on screen (activity)
//jsonParsed.setText(OutputData);
}
}
}
}
I changed send PostRequest with this code: //SEND Get data reques HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET");& it works
I am trying to invoke the POST API of personality insights from Android on a button click and display the response on the screen after proper parsing. The API details of the personality insights are here.
When I tried to test this using POSTMAN I am getting the correct response. But when I try to invoke this from Android, the logcat is not showing any error and the application doesn't terminate in the emulator. The initial invocation of API is not working for me.
I referred this link for the android code
This is the code which I used. Please let me know of any mistakes that I have made.
Edited :
I also tried this example link but everything seems to be deprecated for my current android API versions.
HTTP Example.java
package com.example.httpexample;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView, button;
TextView textView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
button = (TextView)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener(){
// When user clicks button, calls AsyncTask.
// Before attempting to fetch the URL, makes sure that there is a network connection.
#Override
public void onClick(View v) {
String stringUrl = "https://gateway.watsonplatform.net/personality-insights/api/v2/profile" (https://gateway.watsonplatform.net/personality-insights/api/v2/profile%27);
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageTask().execute(stringUrl);
} else {
textView.setText("No network connection available.");
}
}
});
}
public TextView getTextView()
{
TextView txtView = (TextView)findViewById(R.id.textView2);
return txtView;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
DownloadWebpageTask.java
package com.example.httpexample;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;
class DownloadWebpageTask extends AsyncTask<String, Void, String> {
private static final String DEBUG_TAG = "HttpExample";
#Override
protected String doInBackground(String... urls) {
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String downloadUrl(String myurl) throws IOException, JSONException{
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setRequestMethod("GET");
final String basicAuth = "Basic " + Base64.encodeToString(""username":password".getBytes(), Base64.NO_WRAP);
conn.setRequestProperty ("Authorization", basicAuth);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
System.out.println("first connection");
JSONObject contentItems = new JSONObject();
contentItems.put("id", "");
contentItems.put("userid", "");
contentItems.put("created", "int");
contentItems.put("updated", "int");
contentItems.put("contenttype", "");
contentItems.put("charset", "");
contentItems.put("language", "int");
contentItems.put("content", "Hi. This is the sample input");
contentItems.put("parentid", "");
contentItems.put("reply", false);
contentItems.put("forward", false);
System.out.println("connection done");
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
System.out.println("Content " + contentAsString);
MainActivity obj = new MainActivity() ;
TextView tv = obj.getTextView();
tv.setText(contentAsString + response);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
It does not seem you are sending your contentItems object anywhere - you populate it, but never include it as payload in the request.
In addition, this contentItems is just one item object you need to include in the JSON input. The JSON input should look like:
{ "contentItems": [ <item1>, <item2> ] }
and you are just creating something that fits as one of the items above.
If you are passing some simple input to the API, I would suggest you include the header Content-Type: text/plain and forget about JSON formatting for the moment, as it is going to be simpler.
I'm trying to connect to a servlet in localhost from my Android Emulator.
I created a project in Eclipse named SimpleHttpGetRequest with an activity named "HttpGetServletActivity".
I created in NetBeans a project named "HttpGetRequest" containing a servlet.
The code in my "HttpGetServletActivity" activity is :
package com.mobdev.simplehttprequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpGetServletActivity extends Activity implements OnClickListener {
Button button;
TextView outputText;
public static final String URL = "http://10.0.2.2:8080/HttpGetRequest/HelloWorldServlet";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[]{ URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("get");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}
}
The source code of my servlet is :
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
public HelloWorldServlet() {
super();
}
#Override
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello Android !!!!");
}
}
I deployed my servlet in Apache server (i'm using xampp);
I added permission for network connection
When I run my App and click on the button, the App crashes, and I don't know why !!
Can anybody help me, please ? Im' stuck.
I tried :
Wifi connection : I did run my App on a real device, instead of "10.0.2.2" I put the ip adress of my PC but it doesn't work ;
Access to project HttpGetrequest from Android Emulator browser, it worked ;
hi i am new learner of android and java.below this is my code. I having trouble to know where is the problem.
when i debug few times, it automatically enter debug mode after that. to fix that i have to restart the phone again. I check with other apps, it work just fine. just for the apps that i currently working on.
problem :
1. if i didn't enter data into the "dateTo" the program will stopped.
2. enter debug mode itself.
3. when i get the data from the array atList, then i key in another 'dateTo" to retrieve another data, but it doesn't replace the current data value. tq
package com.example.m2mai;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class RetrieveActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
}
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
public void getStream(View v)
{
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... params)
{
return getData();
}
public long getDateTo()
{
EditText toText = (EditText)findViewById(R.id.dateTo);
String To = toText.getText().toString();
DateFormat dateFormatTo = new SimpleDateFormat("dd/MM/yyyy");
Date dateTo = null;
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
long timeTo = dateTo.getTime();
new Timestamp(timeTo);
return timeTo/1000;
}
protected String getData()
{
String toTS = ""+getDateTo();
String decodedString="";
String returnMsg="";
String request = "http://api.carriots.com/devices/{API_KEY}/streams/?order=-1&max=2&at_to="+toTS;
URL url;
HttpURLConnection connection = null;
try {
url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
//establish the parameters for the http post request
connection.addRequestProperty("carriots.apikey", "somekey");
connection.addRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
//create a buffered reader to interpret the incoming message from the carriots system
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((decodedString = in.readLine()) != null)
{
returnMsg+=decodedString;
}
in.close();
connection.disconnect();
JSONObject nodeRoot = new JSONObject(returnMsg);
JSONArray res = nodeRoot.getJSONArray("result");
for (int i = 0; i < res.length(); i++)
{
JSONObject childJSON = res.getJSONObject(i);
if (childJSON.get("data")!=null)
{
String value = childJSON.getString("data");
dataList.add(value);
JSONObject node=new JSONObject(value);
atList.add(node.get("temperature").toString());
}
}
}
catch (Exception e)
{
e.printStackTrace();
returnMsg=""+e;
}
//Log.d("returnMsg",returnMsg.toString());
return returnMsg;
}
protected void onPostExecute(String result)
{
//show the message returned from Carriots to the user
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
EditText myData=(EditText)findViewById(R.id.editText2);
myData.setText(atList.get(1));
}
}
}
This line long timeTo = dateTo.getTime(); will throw a NullPointerException when the dateFormatTo.parse method throws a ParseException. This is going to happen when you come into the method with the To string not matching the specified format.
You're not exiting out of the flow so the long...getTime(); line runs, but dateTo is null resulting in a crash.
In the onPostExecute; you aren't verifying that atList has multiple elements. A JSON parse failure will leave atList empty and cause an index bounds exception for those 2 get calls.
These may not be the solutions to what you're seeing; but they will crash the app when these are hit in very likely situations; including the one you describe of an empty string for To.
As the comments mention; the logs will help see what's actually happening; but this is too big for a comment and those points are going to cause problems.
package com.yarin.android.Examples_08_01;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
//以Get方式上传参数
public class Activity03 extends Activity {
private final String DEBUG_TAG = "Activity03";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
TextView mTextView = (TextView) this.findViewById(R.id.TextView_HTTP);
// http address "?par=abcdefg" is the argument to be posted
String httpUrl = "http://192.168.0.100:8080/httpGet.jsp?par=test";
// 获得的数据
String resultData = "";
URL url = null;
try {
// 构造一个URL对象
url = new URL(httpUrl);
} catch (MalformedURLException e) {
Log.e(DEBUG_TAG, "MalformedURLException");
}
if (url != null) {
try {
// 使用HttpURLConnection打开连接
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 得到读取的内容(流)
InputStreamReader in = new InputStreamReader(
urlConn.getInputStream());
// 为输出创建BufferedReader
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
// 使用循环来读取获得的数据
while (((inputLine = buffer.readLine()) != null)) {
// 我们在每一行后面加上一个"\n"来换行
resultData += inputLine + "\n";
}
// 关闭InputStreamReader
in.close();
// 关闭http连接
urlConn.disconnect();
// 设置显示取得的内容
if (resultData != null) {
mTextView.setText(resultData);
} else {
mTextView.setText("读取的内容为NULL");
}
} catch (IOException e) {
Log.e(DEBUG_TAG, "IOException");
}
} else {
Log.e(DEBUG_TAG, "Url NULL");
}
Button button_Back = (Button) findViewById(R.id.Button_Back);
/* 监听button的事件信息 */
button_Back.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
/* 新建一个Intent对象 */
Intent intent = new Intent();
/* 指定intent要启动的类 */
intent.setClass(Activity03.this, Activity01.class);
/* 启动一个新的Activity */
startActivity(intent);
/* 关闭当前的Activity */
Activity03.this.finish();
}
});
}
}
For the above code, I understand how it works. It runs as an application and needs to communicate with a web server.
But I don't know how to make a web server which could be a container of "http://192.168.0.100:8080/httpGet.jsp".
I did some investigation.
(1) On Android phone, i-jetty, kws, atieews may help, but I failed to make them work for my purpose.
(2) On PC, tomcat is a good candidate to be as jsp container. But it provides localhost:8080 address, that means only application runs on PC could communicate with it. Am I right? How to make my Android phone to connect tomcat (runs on my PC)?
(3) Any other idea?
Thanks!
To make a server which can communicate with your android app you can use SOAP services or JSON. Those two are the most used ones (JSON is faster and in my opinion better to use but this can be discussed).
Take a look on some tutorials on how to create the server side app for your android app.
This is not an easy taski if you newer set up a server.