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

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");

Related

Response 301 Moved Permanently

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");

Unable to send json with HttpURLConnection

I have been looking at this over a week now and i cant find where the null pointer problem lies, this is bugging me completely and the teacher Google is not very helpful. I cant find what the real problem here...and its driving nuts! :/
I am trying to send a notification to Firebase and it does not go beyond the streamwriter, i have checked that conn is not null or the json but they are all looking good. If i use a RESTclient i can send a message successfully with correct ID key and message and it is recived by the app. The emulated phone has internet connection.
The error thrown in run looks like this:
com.android.okhttp.internal.huc.HttpURLConnectionImpl:https://fcm.googleapis.com/fcm/send. Attempt to invoke interface method 'void om.android.okhttp.internal.http.HttpStream.writeRequestHeaders(com.android.okhttp.Request)' on a null object reference.
my code:
String FCM_URL = "https://fcm.googleapis.com/fcm/send";
URL url = new URL(FCM_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
//set method as POST or GET
conn.setRequestMethod("POST");
conn.setConnectTimeout(3000);
//pass FCM server key
conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
//Specify Message Format
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
//Create JSON Object & pass value
JSONObject infoJson = new JSONObject();
infoJson.put("body", message);
infoJson.put("title", "Test send:");
JSONObject json = new JSONObject();
json.put("to", tokenId);
json.put("collapse_key", "type_a");
json.put("notification", infoJson);
//Add data to json string
JSONObject datacon = new JSONObject();
datacon.put("body","First notification");
datacon.put("title", "Collapsing A");
datacon.put("key_1","Data for key 1");
datacon.put("key_2","Hello, test two");
json.put("data", datacon);
BufferedWriter out =
new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
out.write(json.toString());
out.flush();
out.close();
Any help or pointers would be greatly appreciated!
It seems there is a typo, set instead of add
conn.setRequestProperty("Content-Type", "application/json");
and after that, to be able to write
conn.connect();

Sending JSON object to API by using http post

I want to add header "Content-Type" "application/json". But I am not been able to do this due to api 23 in android.
OutputStream os= null;
os=httpclient.getOutputStream();
BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(os));
JSONObject jsonobj = new JSONObject();
jsonobj.put("Name","alpha");
jsonobj.put("Status","Active");
jsonobj.put("Type","Admin");
jsonobj.put("Address","beta");
jsonobj.put("Password","333");
jsonobj.put("PhoneNumber",123);
bw.write(jsonobj.toString());
os.close();
I assume that you are trying to make a network call to some API which expects you to add Headers to the HTTP calls you are making and the content-type data is JSON.
If that is your case then you would have to specify the Headers to the instance to respective class with which you are trying to connect..
for example if you are using HttpURLConnection
then it would look like this
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST"); // hear you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
httpURLConnection.connect();
and when you are posting some data to the instance of the HttpURLConnection you can do it like this...
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("para_1", "arg_1");
jsonObject.addProperty("para_2", "arg_2");
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();

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()).

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