Response 301 Moved Permanently - android

I used to get the following response to php request
Response:
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>
my code:
URL url = new URL("http://myappdemo.com/payumoney/payUmoneyHashGenerator.php");
// get the payuConfig first
String postParam = postParams[0];
byte[] postParamsByte = postParam.getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("Content-Length",
String.valueOf(postParamsByte.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postParamsByte);
InputStream responseInputStream = conn.getInputStream();
StringBuffer responseStringBuffer = new StringBuffer();
byte[] byteContainer = new byte[1024];
for (int i; (i = responseInputStream.read(byteContainer)) != -1; ) {
responseStringBuffer.append(new String(byteContainer, 0, i));
}
Log.e("tag", "doInBackground: "+ responseStringBuffer.toString());
also tried with volley reponse was
BasicNetwork.performRequest: Unexpected response code 301 for
http://myappdemo.com/payumoney/payUmoneyHashGenerator.php
.
Please help me.
Thanks in Advance.

301 Moved Permanently is used for permanent URL redirection.Current links using the URL that the response is received for should be updated. try to use https:// in your link
use URL url = new URL("https://myappdemo.com/payumoney/payUmoneyHashGenerator.php");

Related

Some character didn't post with Json Post - getting 500 reponse

I have prepared one API, and I want to send one specific data with json posting.
My code works fine during working with Fiddler or site side.
But the problem is why some character didn't send, when we use Android version as a client device.
For example:
string a="mn✈" // correct on any device (android,site,Fiddler,...)
string b="mn✉" //correct on any device except(android) //getting 500 reponse
String requestURL = Utils.SERVER_URL + "PostJsonFeatures";
HttpURLConnection conn = (HttpURLConnection) new URL(requestURL).openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
JSONObject postDataParams = new JSONObject();
postDataParams.put("Features", getAttributes());
postDataParams.put("productId", productId);
postDataParams.put("groupId", catId);
postDataParams.put("brandId", PrefManager.getInstance(context).getCompanyId());
postDataParams.put("languageId", PrefManager.getInstance(context).getLanguageApi());
DataOutputStream printout = new DataOutputStream(conn.getOutputStream ());
printout.write(postDataParams.toString().getBytes());
printout.flush ();
printout.close ();
You can decode to string and pass in url.
String parseString = URLDecoder.decode(URLEncoder.encode(myString, "UTF-8"), "ISO-8859-1");

Deleting file from Parse.com usung REST API in Android

Why can't I delete a file from parse.com? Here is my method.
URL url = new URL("https://api.parse.com/1/files/"+ parseFileName);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty ("X-Parse-Master-Key", Sett.PARSE_MASTER_KEY);
conn.setRequestProperty ("X-Parse-Application-Id", Sett.PARSE_APP_ID);
conn.setRequestProperty ("X-Parse-REST-API-Key", Sett.PARSE_REST_KEY);
conn.setRequestProperty ("Content-Type", "application/json");
conn.setRequestMethod("DELETE");
String responseStr = conn.getResponseMessage();
String responseCode = String.valueOf(conn.getResponseCode());
Result = 200 OK, but the file is still available for download. Also, I tried to send a request through the control panel from Parse.com. Result was null
This is a link to file I triying to delete http://files.parsetfss.com/5592cbfd-6fd4-41ca-8a82-dd90ebcd6541/tfss-410de5c1-bbac-4772-8be5-45b4f55d47fd-1450985755273

POST function for REST service returns empty response

I'm trying to do a post method for a REST service, but I'm not getting any response from server:
public JSONObject postValues (String strUrl, String strJsonArray) throws Exception{
JSONObject jsonObject = null;
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
strJsonArray = "data=" + strJsonArray;
Log.e("result",""+strJsonArray);
OutputStream os = conn.getOutputStream();
os.write(strJsonArray.getBytes());
os.flush();
conn.connect();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
Log.e("output",output);
sb.append(output);
}
Log.e("output",sb.toString());
jsonObject = new JSONObject(sb.toString());
conn.disconnect();
return jsonObject;
}
When I see my logCat a get:
output {}
I know that the server is working right because I'm using the "advanced REST client" plugin of google chrome. If I call the URL manually (using the plugin of course)I get the desired answer:
{"message":"OK","code":200}
But if I try to use my function, my strJsonArray is inserted but I get an empty respond from server.
Is there anything wrong with my code?.
Everything looks good...
You could use Wireshark to capture the packets sent to and received from the server using an emulator and the chrome rest client. Then you can compare them and maybe find out what's wrong.
You could also check if theres something in the error stream (conn.getErrorStream()).

Android - Login HTTP works API 10 Only

To get some information, my app emulates the behaviour of a web browser. The log-in session of the target website has 3 steps:
Access the form (gives a cookie for authentication)
Send a POST request with all information
The server answers contains a link in the headers that indicates the address to go to
I have three functions for that, one that gets the page and extracts the session Cookie.
The second one extracts the form of this first page and puts the right infos.
The third one prepares the POST request, sends it, and read the Location in the headers.
It works fine... But with API 10 only.......
Does anyone know what has changed after API 10??
I've tried on Emulators with API 13 or more, and at the moment of sending the POST request, the server answers as if the Cookie given in the first page is not valid. (I get an answer Code of 200, and the login page... Instead of a 302 answer and the Location to follow).
I use the java.net CookieManager & CookieHandler
Here is the first function for example:
private String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4");
conn.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
if (MainActivity.cookies != null) {
for (String cookie : MainActivity.cookies) {
conn.setRequestProperty("Cookie", cookie);
}
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
And this is the third function (nothing special in the second one:
private void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpURLConnection) obj.openConnection();
// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4");
for (String cookie : MainActivity.cookies) {
System.out.println("Adding Cookie: "+cookie);
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
// Update Progress bar -> 25
mProgression += 5;
msg = mHandler.obtainMessage(PROGRESSION, mProgression, 0);
mHandler.sendMessage(msg);
conn.setDoOutput(true);
conn.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
System.out.println("Attempt to get location");
// Get the location of the ticket in the ResponseHeader
setLocation(conn.getHeaderFields().get("Location"));
// Get the Cookie of the ResponseHeader AFTER sending credentials
setLoginCookies(conn.getHeaderFields().get("Set-Cookie"));
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// System.out.println(response.toString());
}
There is no problem with the log cat, the third function can't go past the "get("Location")" since the server doesn't return any location...
Thanks to whoever takes time to answer that one...
Btw, it's my first app :)
Thanks again!
I think you should use a better client that will handle all the headers and the body by itself, you can use android built in HTTP client but it can not persist cookies, or you can use loopj async client that works great.
Actually I published a post that explained how we did it, you can read it here.

Basic authentication to access assembla rest apis from android

I want to use assembla apis from android environment for my project.
I am trying to do basic authentication as follow :
String authentication = "username:password";
String encoding = Base64.encodeToString(authentication.getBytes(), 0);
URL url = new URL("https://www.assembla.com/");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + encoding);
conn.setDoOutput(true);
conn.connect();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
I am getting 400 and Bad Request in output.
is there something wrong with URL that i am using or some other thing is going wrong?
It looks like the question was answered here. You need to use Base64.NO_WRAP flag when encoding username-password pair:
String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
By default the Android Base64 util adds a newline character to the end of the encoded string. This invalidates the HTTP headers and causes the "Bad request".
The Base64.NO_WRAP flag tells the util to create the encoded string without the newline character thus keeping the HTTP headers intact.
REST API with HTTP Authentication Output:- I got the result
String authentication = "username:password";
String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", "Basic " + encoding);
conn.connect();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
Content = sb.toString();

Categories

Resources