The url which I give gets redirected. When i hit the url with some browser it redirects to another site. When i test it in some rest client i am getting http code 302, which is correct for redirect. But i try the same with below code, it returns 200. Can somebody help me out ?Thanks in advance.
updated url.
try {
URL url = new URL("https://securestore.hbo.com/cart.php?f=pplogin&ppx=1&method=checkout");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int code = connection.getResponseCode();
System.out.println(connection.getResponseMessage());
System.out.println("code is" + code);
connection.disconnect();
}
catch (MalformedURLException e) {
e.printStacTrace();
}
catch (IOException e) {
e.printStackTrace();
}
If url1 is being redirected to url2, then you will get 302 status. However if you code is directally calling url2, you are bound to get 200.
Try the following code.
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
.....
connection = (HttpConnection)Connector.open(url);
responseCode = connection.getResponseCode();
Try adding a response with the 302 code you want. Something like connection.setStatus(statusCode) I may be wrong though.
The HttpURLConnection will follow the redirects by default.
Try setting the following if you do not wish to follow redirects:
HttpURLConnection.setFollowRedirects(false);
For example, in relation to your code:
try {
URL url = new URL("");
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int code = connection.getResponseCode();
System.out.println(connection.getResponseMessage());
System.out.println("code is" + code);
connection.disconnect();
}
catch (MalformedURLException e) {
e.printStacTrace();
}
catch (IOException e) {
e.printStackTrace();
}
Related
I have a simple web api which receives a parameter as string and return a "success" string as response.
I have tested the api url with POSTMAN App and I got response as "success"
url : http://www.xxx.co/testapi/testmethod
Method : POST
Params : key=val ; value=Hai
Postman return as : "success"
My code in android is:
public static String tryPOSTScript(){
Log.d("TAG","App1 inside tryPOSTScript");
String data = "val=Hai";
URL url = null;
try {
url = new URL("http://www.xxx.co/testapi/testmethod");
} catch (MalformedURLException e) {
Log.d("TAG","App1 Exception MalformedURLException: "+e.toString());
e.printStackTrace();
}
HttpURLConnection con = null;
try {
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.getOutputStream().write(data.getBytes("UTF-8"));
con.getInputStream();
} catch (IOException e) {
Log.d("TAG","App1 Exception IOException: "+e.toString());
e.printStackTrace();
}
return data;
}
And I got the response as
Exception IOException: java.io.FileNotFoundException: http://www.xxx.co/testapi/testmethod
Exception responseCode: 404
Please help to correct it. If file not found How can I get it correctly with postman app?
I've tried to download HTML content from the URL http://google.com and another URL.
I tried:
URL url = new URL("http://google.com/");
urlConnection = (HttpURLConnection) url.openConnection();
And although I've tried InputStream, it didn't work the same.
try {
URL url = new URL("http://google.com/");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
System.out.print(urlConnection.getResponseCode());
}
catch (Exception e)
{
System.out.print("Error: "+e.getMessage());
}
finally {
urlConnection.disconnect();
}
At the end I see the catch and the e.getMessage is null. If I debug it, urlConnection.getResponseCode() is returning -1.
You set DoOutput where you will not do output. You do not set DoInput where you do input. Remove the chunked streaming mode.
I am making map app(Android) and i need to make on-click markers with street address in info. After few bad attempts i saw that Geocoder /get from location doesn't work anymore(returns an empty array with null pointer).
I found out here
LINK that i can do a HTTP/S request to google and i will get back JSON/XML.
My question is: how to make the HTTP request(example) when HTTP client is depricated? Can you give me an example of code to send the request and work out the response in JSON(or at least sending only)?
EDIT: I am getting this:android.os.NetworkOnMainThreadException
try {
URL url = new URL(baseUri+builder.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect(); \\exception originated here
is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is));
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
jsonresponse = new JSONArray(builder.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Deprecated is only Apache HTTP client. But you can always use HttpURLConnection for HTTP requests.
There is a training material with a code example.
http://developer.android.com/training/basics/network-ops/connecting.html
I added a self signed-certificate (https) manually in Settings-> Security-> Trusted certificates.
And if i try to access to my server using google chrome runs OK (previosly accept message). But in my Android application, using HttpsURLConnection class,crashes.
This is my code:
try {
URL obj = new URL(url);
HttpsURLConnection conn;
conn = (HttpsURLConnection) obj.openConnection();
conn.setConnectTimeout(timeOut);
conn.setRequestMethod("GET");
StatusCode = conn.getResponseCode();
Log.i(TAG_GET, "Status Code: " + StatusCode);
InputStream body = null;
try {
body = conn.getInputStream();
} catch (Exception e) {
e.printStackTrace();
body = conn.getErrorStream();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I think that I need load certificates installed on my device, but how can I do?
Thanks
I'm using this script to try to send POST data to a PHP script from my Android app. But it doesn't even let me Run it due to the error "loginUrl cannot be resolved". Since other people seem to have got this code working, have I missed something obvious here? Here's the code but changed by me (see it with comments by the link above):
public void postData() {
URL url;
HttpURLConnection conn;
try{
url=new URL("http://mysite/test.php");
String param="param1=" + URLEncoder.encode("value1","UTF-8")+
"¶m2="+URLEncoder.encode("value2","UTF-8")+
"¶m3="+URLEncoder.encode("value3","UTF-8");
conn=(HttpURLConnection)loginUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.close();
String response= "";
Scanner inStream = new Scanner(conn.getInputStream());
while(inStream.hasNextLine())
response+=(inStream.nextLine());
}
catch(MalformedURLException ex){
Toast.makeText(GameButton.this, ex.toString(), 1 ).show();
}
catch(IOException ex){
Toast.makeText(GameButton.this, ex.toString(), 1 ).show();
}
}
Thanks!
You have declared the variable as url but you are trying to use it as loginUrl.
Check these declaration and initilization in your code
URL url;
url=new URL("http://mysite/test.php");
and problem here when you try to open the connection:
conn=(HttpURLConnection)loginUrl.openConnection();
it should be
conn=(HttpURLConnection)url.openConnection();