Android CouchDB {"error":"bad_request","reason":"invalid_json"} - android

While trying to Create a new Document in my IrisCouch Database, i am always getting following error:
{"error":"bad_request","reason":"invalid_json"}
This is the relevant part of my function:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://username.iriscouch.com:6984/mydb");
StringEntity entity = new StringEntity(body);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.toString()) ;
HttpEntity httpEntity = httpResponse.getEntity();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
System.out.println("body: " + body);
} catch (Exception e) {
e.printStackTrace();
}
Here is my System.out of "body":
{"bild1":"","bild2":"","bild3":"","bild4":"","bild5":"","bild6":"","bild7":"","bild8":"","bild9":"","bild10":"","name":"","plz":0,"ort":"","strasse":"","n_koordinate":0,"e_koordinate":0,"beschreibung":"","groesse":"< 50m²","sitzplaetze":"< 50","grillstellen":"1","reservierung":false,"res_name":"","res_tele":"","res_weiteres":"","wc":true,"behindi":false,"dach":true,"kinderfreundl":false,"auto":false,"kinderwagen":false,"einkauf":false,"datum":"2015-07-01-14:12:01:856","bewertung":0,"anz_bewertung":0}
The JSON is valid. Tested it with jsonlint.com JSON Validator.
What could i do? Thanks in advance!

Perhaps the unicode superscript 2 (²) is bothering it?
Not sure which library this HttpPost is, but seems a lot like the HttpWebRequest, so try setting your header this way:
httpPost.setHeader("Content-type", "application/json charset=utf-8");
It could also be that the HttpPost class doesn't properly encode strings.
(I haven't pasted this in my Visual studio, so just a shot in the dark)

Related

Get the XML entity passed in body - HTTP Put method in Android

I wanted to retrieve the XML entity passed in body of HTTP Put method. I used the below code,
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(serverSocket.accept(), new BasicHttpParams());
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
System.out.println(EntityUtils.toString(entity));
I could get the norma strings, but when trying to pass the XML entity, I could not even see the print statement.
I hope this code help you.
HttpPost httppost = new HttpPost(SERVICE_EPR);
StringEntity se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse =
(BasicHttpResponse) httpclient.execute(httppost);
response.put("HTTPStatus",httpResponse.getStatusLine().toString());
PFB the solution,
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
params = new BasicHttpParams();
conn.bind(socket, params);
//Extracting the information from the requested URI
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity httpEntity = ((HttpEntityEnclosingRequest)request).getEntity();
if(httpEntity != null){
InputStream instream = httpEntity.getContent();
try {
// do something useful
String myString = IOUtils.toString(instream, "UTF-8");
Log.e(TAG,">>>> http body > "+myString);
} finally {
instream.close();
}
}
Don't put any log or print statements using the data you received, I was getting 'Content already consumed' exception. I had used several logs using the httpEntity i received and that was causing the problem for me. I commented those(marked yellow) and started working.
PF the Apache doc for reference,
http://hc.apache.org/httpcomponents-core-ga/tutorial/pdf/httpcore-tutorial.pdf

cUrl HttpPost parameters not recognized(?) by server

I am trying to fetch an authorization key from a server. In the documentation they state that I can retrieve one by executing the following curl command:
$ curl --data "grant_type=authorization_code&code=603372224265" https://gerard2.zportal.nl/api/v2/oauth/token`
I have followed the instructions from stackoverflow and produced the following:
#Override
protected String doInBackground(String... params) {
mAuthorizationCode = params[0];
mSchoolCode = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://" + mSchoolCode + ".zportal.nl/api/v2/oauth/token");
try{
List<NameValuePair> nameValuePairs = new ArrayList<>(2);
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader("Accept", "application/json");
nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
nameValuePairs.add(new BasicNameValuePair("code", mAuthorizationCode));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpParams parameters = httppost.getParams();
HttpConnectionParams.setConnectionTimeout(parameters, 45000);
HttpConnectionParams.setSoTimeout(parameters, 45000);
HttpResponse response = httpClient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while((line = reader.readLine()) != null){
Log.e(LOG_TAG, line);
}
}catch(ClientProtocolException e){
Log.e(LOG_TAG, "Error", e);
}catch(IOException e){
Log.e(LOG_TAG, "IO Error", e);
}
return null;
}
The response the server sends me is:
E/ScheduleRetriever: {"response":{"status":500,"message":"Intern probleem op het portal.","details":"class org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'grant_type' is not present","eventId":767369,"startRow":0,"endRow":0,"totalRows":0,"data":[]}
While I did include the POST_parameter "grant_type". Can someone help me figure out why the server says that it did not receive the parameter grant_type?
Thanks.
*EDIT: The code I used expired apparently. Generated a new one and it totally works. Thanks!
You shouldn't be overriding the Content-Type of the POST request to application/json using the line httppost.setHeader("Content-Type", "application/json");
This is most likely causing the server to misinterpret the data since the Content-type of the request should be application/x-www-form-urlencoded.
Remove the following line and it should work:
httppost.setHeader("Content-Type", "application/json");

Android HttpPost without parameter name

I've used POST methods many times in the past but got this weird web service. It works fine on a chrome extension but i am unable to get this response using android . Please add anything in the code if missing
Here is the code i am using
HttpParams param = new BasicHttpParams();
param.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(param);
HttpPost httppost = new HttpPost(url);
Utils.showLogs(MyConstants.TAG, "ApplicationURL: " + url);
httppost.setHeader("Content-type", contentType);
HttpConnectionParams.setConnectionTimeout(param, MyConstants.WEBSERVICE_TIMEOUT);
HttpConnectionParams.setSoTimeout(param, MyConstants.WEBSERVICE_TIMEOUT);
String response = null;
try {
if (jsonObject == null) {
StringEntity entity = new StringEntity(json, HTTP.UTF_8);
httppost.setEntity(entity);
} else {
StringEntity stringEntity = new StringEntity(jsonObject.toString());
httppost.setEntity(stringEntity);
}
// Execute HTTP Post Request
HttpResponse httpResponse = httpclient.execute(httppost);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return MyConstants.SERVER_NOT_RESPONDING;
}
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Thanks
Did you add <uses-permission android:name="android.permission.INTERNET" /> in AndroidManifest.xml ?
If not, add this should be fine!

Android http post works with string but not xstream

I'm making a droid app that uses a web service. I have it working when I pass in a string, but when I try and use Xstream it doesn't work. I have printed out the xml strings from both the Xstream and my own and they are identical. Without xstream it looks like this and works
`HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g6/login.php");
Boolean response = false;
try
{
String test = "<Login>" +
"<password>" + "lernrane" + "</password>" +
"<user_name>" + "jake#jake.com" + "</user_name>" +
"</Login>";
StringEntity se = new StringEntity(test,
HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setEntity(se);
System.out.println("MADE IT TO RESPONSE");
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
String resp = EntityUtils.toString(resEntity);
System.out.println(resp);
response = convertToBool(resp);`
But when I use xstream it looks like this and fails
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g6/login.php");
Boolean response = false;
try
{
LoginObject login = new LoginObject();
login.setUserName("jake#jake.com");
login.setPassword("lernrane");
XStream xstream = new XStream();
xstream.alias("Login", LoginObject.class);
String xml = xstream.toXML(login);
System.out.println(xml);
StringEntity se = new StringEntity(xml,
HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setEntity(se);
System.out.println("MADE IT TO RESPONSE");
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity resEntity = httpresponse.getEntity();
String resp = EntityUtils.toString(resEntity);
System.out.println(resp);
response = convertToBool(resp);
My web service looks like this
$dom = new domDocument;
$dom = simplexml_load_file('php://input');
$xml = simplexml_import_dom($dom);
$user = Users::find_by_user_name($xml->user_name);
if($user)
{
if($user->password == $xml->password)
{
echo "TRUE";
}
}
else
echo "FALSE";
Ignore the odd looking query, I am using active record and I know it works correctly...thanks
I figured it out... When I printed out my xml user_name looked like this user__name eventhough it was clearly named user_name. There must be some type of char set conflict so I just renamed it without the underscore.

Sending Video using HTTP Post Multipart entity

What I want I want to send a video from my SDcard to a server. I also want to send some parameters/value with it.
I have tried I have tried the following code:
public String SendToServer(String aUrl,File aFile)
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(aUrl);
try
{
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(aFile));
entity.addPart("video[title]", new StringBody("testVideo"));
entity.addPart("video[type]", new StringBody("1"));
httpPost.setEntity(entity);
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, Globals.sessionCookie);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
String Response = "";
if (response != null)
{
Response = EntityUtils.toString(resEntity);
}
return Response;
}
catch (IOException e)
{
e.printStackTrace();
}
return "Exception";
}
What is the problem When I run this code, I get stuck at this line
HttpResponse response = httpClient.execute(httpPost, localContext);
I get no exception, no response nothing at all. Can anyone please guide me, what is the problem in here?
The above code in my question was perfect, but I had the network problem. My device was connected to a hotspot(Connectify Software). When I connected to the original network, this code worked perfect.
I recommend you people to never trust a hotspot for this kind of functionality.
try using this way if want to send as content or esle I will upload the project by tonight
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(filePath), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);

Categories

Resources