HI,
I need to use http post method for web-service in android application .But in android shows error when use this method .How to use this method in application or any other equal method for replacing this http post method.
thanks,
Lakshmanan.
URL url = new URL(my_ip_address);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("METHOD", "POST");
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//do your stuff
}
Related
I have responseCode = 403.
Do you see any issue in the code below?
I tried every flag in the Base64.encode.
My site woks perfectly fine: once I login in manually from http passing my username/passwd, I'm able to retrieve the JSON data using https.
Do you think I'm correct in suspecting an authorization issue?
URL object = new URL("https://aaaaaa.bb/api/?format=json" );
HttpURLConnection connection = (HttpURLConnection) object.openConnection();
connection.setReadTimeout(60 * 1000);
connection.setConnectTimeout(60 * 1000);
connection.setRequestMethod("GET");
String authorization="xxxxxx#gmail.com:yyyyyy";
String encodedAuth="Basic "+ Base64.encode(authorization.getBytes(), Base64.DEFAULT);
connection.setRequestProperty("Authorization", encodedAuth);
connection.connect();
int responseCode = connection.getResponseCode();
Can you try by setting the content type:
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
I'm trying to have my android app execute code where it opens a URL connection to a local php file that returns database entries in JSON format, but it's not connecting, after commenting out the other lines I can see that it throws an exception at the lines:
connection = (HttpURLConnection) url.openConnection();
connection.connect();
Heres the screen shot of android code and the error log, the returned expected json file in windows and the php file:
link
Can you change your
URL url = new URL(getListUrl);
into
URL url = new URL("http://www.google.com");
and check the incoming data.
and the following is a working example.
try {
URL url = new URL("http://www.google.com");
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException("URL Exception");
}
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
resCode = httpConn.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (MalformedURLException e) {
e.printStackTrace();
}
My argument is if this code works for remote urls, it should work with localhost as well.
Hi it must be that you are using wrong local ip address in android files
it should be 10.0.2.2 not 127.0.0.1
First tell me are you testing on emulator or device
if emulator then where you define file path it should be
http://10.0.2.2/request_entries.php
just like in code
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/request_entries.php");
Managed to get the input stream using the URL:
URL url = new URL("http://10.0.2.2/request_entries.php");
result
Thanks a bunch guys :)
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]).
So I am currently writing an android app that will get tweets from a particular user, using Twitter's 1.1 Application-only-auth, which requires a POST HTTP request to get a bearer token. I have a method set up that uses an HttpsURLConnection to open a connection, but
conn.setDoOutput(true); method isn't working
conn.doOutput stays false
the request stays the default GET.
Am I doing something wrong?
This method is called in an AsyncTask's doInBackground() method:
public String getRequestBearerToken(String endUrl) throws IOException {
String encodedCred = encodeKeys("API-key", "API-secret");
HttpsURLConnection connection = null;
try {
URL url = new URL(endUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
// POST request properties
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", getResources()
.getString(R.string.app_name));
connection.setRequestProperty("Authorization", "Basic "
+ encodedCred);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
...
The method disconnect from HttpURLConnection seems not to work properly.
If I execute the following code:
url = new URL("http:// ...");
connection = (HttpURLConnection) url.openConnection ();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
// Some code
connection.disconnect();
connection.setDoInput(false); // -> IllegalStateException
I get an IllegalStateException when I call the method setDoInput. The exception says:
Already connected
It sounds like you're trying to reuse the connection? i.e. altering the request properties after you've disconnected from the server, ready to make another connection.
If that is the case, then just create a new HttpURLConnection object.