I'm trying to parse the json data from an url, when i try to create connection , it throws the exception as
java.net.ProtocolException: cannot write request body after response has been read
I got the response message as Not found.
and i checked the url in web browser it shows the Json data when i login wuth my credentials.
so, i found that i need to add the cookie to my connection, but i don't know how to do this.
public void parseData(String cookie){
HttpUrlConnection connection;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Cookie", cookie);
Log.e(TAG, "cookie " + cookie);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.connect();
Log.e(TAG,connection.getResponseMessage());
/**
here i'm trying to parse the data
using BufferedReader calss
**/
}
catch(IOException e){}
}
i need to add the cookie in connection.
Please help me on this.
According to this link
you can do this:
Values must be set prior to calling the connect method:
URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
URLConnection urlConn = myUrl.openConnection();
Create a cookie string:
String myCookie = "userId=igbrown";
Add the cookie to a request: Using the
setRequestProperty(String name, String value); method, we will add a
property named "Cookie", passing the cookie string created in the
previous step as the property value.
urlConn.setRequestProperty("Cookie", myCookie);
Send the cookie to the server: To send the cookie, simply call connect() on the URLConnection
for which we have added the cookie property:
urlConn.connect()
Related
I have ASP.Net MVC4 WEB API, hosted in local IIS.
I request the api from android using GET method. Response is 405 Action not Allowed.
I Have This Method in Controller :
public IEnumerable<Table> GET()
{
return _repository.GetAll();
}
But When I Change the Method to POST:
public IEnumerable<Table> POST()
{
return _repository.GetAll();
}
and request from android with POST method.
I got the RESULTS.
I request both GET and POST with the same route.
'/api/tables'
In android project, I use HttpUrlConnection to request API.
try{
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000 /* milliseconds */);
conn.setConnectTimeout(7500 /* milliseconds */);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod(method);
conn.setDoInput(true);
if(method == "POST")
conn.setDoOutput(true);
if(params != null){
// Get OutputStream for the connection and
// write the parameter query string to it
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getURLEncodedString(params));
writer.flush();
writer.close();
}
// Starts the query
conn.connect();
What am i doing wrong?
info:
when request from browser Get Method return results and Post Method 405.
The problem is in my android project
Android Developer: HttpUrlConnection
HttpURLConnection uses the GET method by default. It will use POST if
setDoOutput(true) has been called.
stackoverflow: https://stackoverflow.com/questions/8187188/android-4-0-ics-turning-httpurlconnection-get-requests-into-post-requests
May be it's a routing issue. Make some little changes in your WebApi.config of webapi
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
One more important thing here is that with this style of routing, you must use attributes to specify the allowed HTTP methods (like [HttpGet]).
I've already created my HTTPUrlConnection :
String postData = "x=val1&y=val2";
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Set-Cookie", sessionCookie);
conn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));
// How to add postData as http body?
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
I don't know how to set postData in http body. How to do so? Would I better use HttpPost instead?
Thanks for your help.
If you want to send String only try this way:
String str = "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
But if you want to send as Json change Content type to:
conn.setRequestProperty("Content-Type","application/json");
and now our str we can write:
String str = "{\"x\": \"val1\",\"y\":\"val2\"}";
Hope it will help,
Guruparan's link in the comment above gives a really nice answer to this question. I highly recommend looking at it. Here is the principle that makes his solution work:
From what I understand, the HttpURLConnection represents the response body as an OutputStream. So you need to call something like:
get the connection's output stream
OutputStream op = conn.getOuputStream();
write the response body
op.write( [/*your string in bit form*/] );
close the output stream
op.close();
and then carry on your merry way with the connection (which you will still need to close).
I am trying to insert data to a mysql table using the below methods but am not able to do so. Any idea on where I may be going wrong?
Method 1: Using HTTPClient to directly access the URL. Below is the code:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://<lclhst>/GnPServlet/GetNpostServlet/? account=1&password=123");
HttpResponse execute = client.execute(httpPost);
Method 2: Using URL connection to directly access the URL. Below is the code:
URL url = new URL("http://<lclhst>/GnPServlet/GetNpostServlet/? account=1&password=123");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept", "application/octet-stream");
conn.connect();
Method 3: Using Arraylist to pass values.
When i run the URL from the browser i get the success message "Inserted" and the data is inserted into the DB. But the same when tried through the app does not insert data. Below is the servlet code:
private String accountLookup(String acct, String pwd)
{
Connection con = null;
Statement st = null;
StringBuffer msgb = new StringBuffer("");
try
{
// These will vary depending on your server/database
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbone?user=root&password=root");
Statement stmt = con.createStatement();
stmt.executeUpdate("insert into accttbl(address, description, time) values ('test 07-jul',ok,12:12)");
return "Inserted";
}
catch (Exception e)
{
return e.toString();
}
}
The below code inserts data but it opens the browser which I dont want. Also the data insertion is not always successful.
String url = "http://10.0.2.2:8080/GnPServlet/GetNpostServlet";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
conn.setRequestMethod("POST");
Looks like you're sending a POST when the servlet expects a GET (which is what the browser would send if you just paste the URL into the URL bar)
conn.setRequestMethod("GET");
...is most likely what you want since your parameters are encoded in the URL.
Also, are you sure that the spaces in your URL before account should be there?
In my android Application in the first screen user authenticates and servlet replies with a session id ...
in the second screen the user again calls the servlet with the session id added in the url as ;jsession="sessionid" along with the parameters...
but the servlet is not get the session id and is responding as a new session without authentication...
where is the problem?
i am using this code for the connection
URL u = new URL(aurl[0]);
url=aurl[0];
publishProgress(""+20,"Connecting...");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
publishProgress(""+40,"Connecting...");
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
publishProgress(""+45,"Connecting...");
publishProgress(""+40,aurl[0]);
int lenghtOfFile = c.getContentLength();
System.out.println(lenghtOfFile+"lenghtOfFile");
is = c.getInputStream();
I was facing the same problem and found a simple solution.
// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
This is the simplest solution I found. We need to set default CookieManager.
Using java.net.URLConnection to fire and handle HTTP requests is the great blog.
Thanks
adding jseesioid in the url never worked ..
the code worked using this solution
httpsessionmanagement
especially these two...
// Gather all cookies on the first request.
URLConnection connection = new URL(url).openConnection();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
// ...
// Then use the same cookies on all subsequent requests.
connection = new URL(url).openConnection();
for (String cookie : cookies) {
connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
// ...
I have an android application that have to communicate with the server using post method in HTTP. My application work fine whenever i open some other sites having basic page may be html or others but whenever i want to open my server file it gives nothing even though with get method in HTTP.
The blank response from the server can be understandable that what i am getting because i have to send some headers with post method as a request and ashx will send some response to it.
But still as expected by get method in HTTP the basic information of the page have to be retrieved.
for eg. my server url is http://172.17.3.90/RMALite/RLHandler.ashx
and the basic response from the get method have to be like this.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=windows-1252"></HEAD>
<BODY></BODY></HTML>
Unfortunately i am getting nothing
but whenever i changed the url to open other sites it work fine and i got the response in text html format.
So my Question is, Android require some stuff to handle ASP.NET handler or ashx file as compare to other sites or URL's?
I know it late now but other can get benefit. Below is code snippet which help me to get accomplished same issue.
public static String excutePost(String targetURL, String urlParameters) {
//targetURL =http://172.17.3.90/RMALite/RLHandler.ashx
URL url;
HttpURLConnection connection = null;
try {
// Create connection
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", ""
+ Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("method-name", "parameter-value");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// // Send request
DataOutputStream wr = new DataOutputStream(connection
.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String field1 = connection.getHeaderField("field1");
String field2 = connection.getHeaderField("field2");
return anyArray;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
I believe it would be helpful n much appreciated to this post
thanks much
-y