Encoding issue Android / REST /JSON - java

i´m trying to solve encoding issue for response (json) from simple rest service in my app for about one day now, no more ideas..
when i open response in restclient, getting correct result:
Status Code: 200 OK
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 270
Content-Type: application/json; charset=utf-8
Date: Wed, 13 Apr 2016 09:26:39 GMT
Keep-Alive: timeout=15, max=100
Server: Apache
Vary: Accept-Encoding
response:
{"reqStatus": 1,
"articles": [
{
"articleId": "1",
"articleName": "Schüssel 18cm",
"articlePrice": "34.50",
"articleDate": "2016-03-15 17:34:00",
"userZip": "76879",
"userCity": "Ottersheim",
"articleImages": [ ...
for inputstream getting that:
{"reqStatus":1,"articles":[{"articleId":"1","articleName":"Sch\u00fcssel 18cm","articlePrice":"34.50","articleDate":"2016-03-15 17:34:00","userZip":"76879","userCity":"Ottersheim","articleImages":[ ...
code for request:
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestMethod("POST");
if (headers!=null&&headers.length>0){
for (int i=0;i < headers.length;i++){
urlConnection.setRequestProperty(headers[i][0].toString(), headers[i][1].toString());
}
}
urlConnection.connect()
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
BufferedReader streamReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
return new JSONObject(inputStr);
}
any ideas?

Related

getContentLength returns -1 when trying to get XML file

I am new to Android programming and would like to get some help on why getContentLength() returns -1 when I try to get the XML data.
The XML url is
String url = "http://www.systembolaget.se/api/assortment/products/xml";
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lengthOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lengthOfFile);
InputStream input = new BufferedInputStream(url.openStream(), 10240);
File fileDir = getFileFolder(AndroAsync.this);
File file = new File (fileDir, "systembolaget.xml");
FileOutputStream outputStream = new FileOutputStream(file);
byte data[] = new byte[4096];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/ lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
input.close();
All help is much appreciated
Thank you! :)
That server isn't sending a content-length, and the reason is that it is using chunked transfer-encoding.
HTTP/1.1 200 OK
Cache-Control: max-age=78517
Content-Type: application/xml; charset=utf-8
ETag: "bb83f8d6-d015-4df5-a8f6-e37248d8a812"
Server: Microsoft-IIS/8.5
X-Cached: True
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Date: Thu, 14 Apr 2016 05:11:22 GMT
X-Cnection: close
Set-Cookie: lbsession=rd10o00000000000000000000ffff91fbfd15o80; path=/
X-Server: 21
Vary: Accept-Encoding
Transfer-Encoding: chunked

How to get response code of httpPut in java

I am using httpPut to java and I want to get the response code after I execute the command. What it gives me which is "response body" is:
HTTP/1.1 200 OK [Cache-Control: no-cache, no-store, must-revalidate, Pragma: no-cache, Expires: Thu, 01 Jan 1970 00:00:00 GMT, Content-Type: application/json, Transfer-Encoding: chunked, Server: Jetty(8.1.8.v20121106)]
But I only want 200! not the whole thing. Any help?
This is my code by the way:
String url = "http://localhost:80/api/clients/";
String clientID = "1234";
httpclient = new DefaultHttpClient();
HttpPut putRequest = new HttpPut(url + clientID);
putRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
putRequest.setHeader("Charset", "UTF-8");
System.out.println(putRequest);
// Add your data
putRequest.setEntity(new StringEntity(clientID, "UTF-8"));
HttpResponse responseBody = httpclient.execute(putRequest);
HTTPResonse having a method called getStatusLine() which return StatusLine Object.
And StatusLine have a method getStatusCode()
So, all you need to write is
HttpResponse responseBody = httpclient.execute(putRequest);
int resultCode = responseBody.getStatusLine().getStatusCode();//200 in your case
responseBody.getStatusLine().getStatusCode() should give you the responsecode of your request.

XMLHttpRequest java javascript

I try to communicate between javascript and java. My script javascript send a message to java and java send a response.
javascript part:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
alert(xmlhttp.responseText);
}
}
var s = "LIGNE \n 2 \n il fait beau \nEND\n";
xmlhttp.open("POST","http://localhost:6020",true);
xmlhttp.send(s);
java part:
try {
serverSocket = new ServerSocket(6020);
} catch (IOException e) {
System.err.println("Could not listen on port: 6020.");
System.exit(-1);
}
serverSocket.accept()
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
String ligne = "";
while(!(ligne = plec.readLine()).equals("END")){
System.out.println(ligne);
}
bw.write("Il fait beau\n");
bw.flush();
bw.close();
plec.close();
socket.close();
output java :
POST / HTTP/1.1
Host: localhost:6020
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:13.0) Gecko/20100101 Firefox/13.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Referer: http://localhost:8080/test.html
Content-Length: 30
Content-Type: text/plain; charset=UTF-8
Origin: http://localhost:8080
Pragma: no-cache
Cache-Control: no-cache
LIGNE
2
il fait beau
So, I receive correctly the message send by javascript but the alert his always empty. How to response at this message?
I try a lot of possiblity but they don't work. And I don't want to use the servlet, it's to heavy to do that.
Thanks.
Edit:
I did this :
bw.write("HTTP/1.1 200 OK\r\n"+
"Content-Type: text/html; charset=utf-8\r\n"+
"Content-Length: 13\r\n\r\n" +
"il fait beau\n");
and this:
String data = "il fait beau \n";
StringBuilder builder = new StringBuilder();
builder.append("HTTP/1.1 200 OK\r\n");
builder.append("Content-Type: text/html; charset=utf-8\r\n");
builder.append("Content-Length:" + data.length() + "\r\n\r\n");
builder.append(data);
bw.write(builder.toString());
But the alert remain empty. Maybe it's a problem in the javascript.
The javascript needs to see a full HTTP response. Merely sending back characters to it, makes it discard the reply as it is an invalid HTTP response.
In your java code, send back something like this
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: <length of data>
---data here---
Reference
Something like:
StringBuilder builder = new StringBuilder();
builder.append("HTTP/1.1 200 OK\r\n");
builder.append("Content-Type: text/plain; charset=utf-8\r\n");
builder.append("Content-Length:" + data.length() + "\r\n\r\n);
builder.append(data);
bw.write(builder.toString());
Try:
bw.write("HTTP/1.1 200 OK\r\n"+
"Content-Type: text/html; charset=utf-8\r\n"+
"Content-Length: 13\r\n\r\n" +
"il fait beau\n");
HTTP-Headers are separated by \r\n (CRLF). Headers and body is spearated by \r\n\r\n.
Note that you set the length to 13 because you also have to count the \n at the end of your string.
EDIT: It does not work because of the cross-domain-policy. http://localhost:6020 is not the same port as the website which executes your JavaScript and so the xmlhttprequest might not be delivered.

Java - problems with REST client while sending an HTTP request

I am trying to send a GET request to a REST server using Java.
This is the code with some debugging.
URL url = new URL(request);
System.out.println("request url: " + url.toString());
System.out.println("method: " + httpMethod);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod(httpMethod);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
OutputStream os = connection.getOutputStream();
os.flush();
String response = os.toString();
System.out.println("response: " + response);
if (response.length() == 0)
{
throw new MyException("the response is empty");
}
This is the output:
request url: http://www.example.com/api.php/getToken/?api_ver=1&token=&api_key=bf8de053d9b6c540fb12195b4ac1602b0a71788c&sig=e00a59747afc7232207d40087e3765a5
method: GET
response:
com.example.api.client.MyException: the response is empty
As you can see, the response is empty.
But if I try and copy and paste the URL in Firefox I get this output
{"error":220}
and this header:
HTTP/1.1 200 OK
Date: Mon, 15 Nov 2010 11:55:29 GMT
Server: Apache
Cache-Control: max-age=0
Expires: Mon, 15 Nov 2010 11:55:29 GMT
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
Content-Length: 33
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=utf-8
Can you see what it is wrong? How could I debug this code further?
Any help would be very much appreciated.
I think you do not use HttpURLConnection properly (there is no connect()).
Maybe study this example.

HttpClient unable to 302 this link?

I found a URL that httpclient doesn't seem to be handling redirects on:
http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNGrJk-F7Dmshmtze2yhifxRsv8sRg&url=http://www.mtv.com/news/articles/1647243/20100907/story.jhtml
should 302 to:
http://www.mtv.com/news/articles/1647243/20100907/story.jhtml
when I look at the headers in the browser everything looks good:
HTTP/1.1 302 Moved Temporarily
Content-Type: text/html; charset=UTF-8
Location: http://www.mtv.com/news/articles/1647243/20100907/story.jhtml
Content-Length: 258
Date: Wed, 08 Sep 2010 18:40:21 GMT
Expires: Wed, 08 Sep 2010 18:40:21 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Xss-Protection: 1; mode=block
Server: GSE
Set-Cookie: PREF=ID=024209255b405b06:TM=1283971221:LM=1283971221:S=AG-13_7Cjg_EqlRY; expires=Fri, 07-Sep-2012 18:40:21 GMT; path=/; domain=.google.com
Connection: close
However httpclient doesn't seem to give me the final URL. Here is the code I was using
HttpHead httpget = null;
HttpHost target = null;
HttpUriRequest req = null;
String startURL = "http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNGrJk-F7Dmshmtze2yhifxRsv8sRg&url=http://www.mtv.com/news/articles/1647243/20100907/story.jhtml";
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE,HttpClientFetcher.emptyCookieStore);
httpget = new HttpHead(startURL);
HttpResponse response = httpClient.execute(httpget, localContext);
Header[] test = response.getAllHeaders();
for(Header h: test) {
logger.info(h.getName()+ ": "+h.getValue());
}
target = (HttpHost) localContext.getAttribute( ExecutionContext.HTTP_TARGET_HOST );
req = (HttpUriRequest) localContext.getAttribute( ExecutionContext.HTTP_REQUEST );
// STILL PRINTS OUT THE GOOGLE NEWS LINK
finalURL = target+""+req.getURI();
Am I doing something wrong? thanks
Found the answer from the httpclient mailing list...
Google doesn't treat a HEAD and GET the same, so the GET redirects with 302 and the HEAD request gives a 200 OK

Categories

Resources