HttpGet getting text with unwanted characters - java

I have this in my MainActivity.java file:
public static void getLatestVersion() {
try {
String myUri = "http://www.stonequest.de/version.php";
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(myUri);
HttpResponse response = httpClient.execute(get);
String Latest = EntityUtils.toString(response.getEntity());
System.out.println(Latest);
} catch (Exception e) {
e.printStackTrace();
}
}
It gets the text, but it also adds some special characters at the beginning of the text.
This is what I get:
0.1.572
I wish to retrieve the version without any characters as shown by going to the endpoint http://www.stonequest.de/version.php
0.1.572
So how can I fix it?

Querying this URL with Firefox, I can see the same characters in the response body (with Firebug). You should mention the characterset in the toString() method, and use the same as on the server side. Preferably set both to "UTF-8".

Related

Empty request when sending special characters to API with Java

I'm using Java to send http requests to my API which is created using Laravel (5.4). If I send a request without any special characters it all works like a charm. But if there are any 'special' characters like: é, å, ö and such the request in Laravel is empty:
dd(request()->all()) outputs []
I guess this has to do with some wrong settings while creating the request in Java. I couldn't find a solution.
Here is the code responsible for creating the request.
public class HttpClient {
org.apache.http.client.HttpClient client;
public HttpClient() {
client = HttpClientBuilder.create().build();
}
public void post(String json) {
try {
HttpPost request = buildPostRequest(json);
HttpResponse response = createClient().execute(request);
int code = getStatusCode(response);
if (code != 200) {
throw new Exception("Error (" + code + ") on server.");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private org.apache.http.client.HttpClient createClient() {
return HttpClientBuilder.create().build();
}
private HttpPost buildPostRequest(String json) throws Exception {
HttpPost request = new HttpPost("some uri");
request.addHeader("Content-type", "application/json; charset=utf-8");
request.addHeader("Accept", "application/json");
StringEntity params = new StringEntity(json);
params.setContentEncoding("utf-8");
params.setContentType("application/json; charset=utf-8");
request.setEntity(params);
return request;
}
private int getStatusCode(HttpResponse response) {
StatusLine line = response.getStatusLine();
return line.getStatusCode();
}
}
EDIT
Dump of the request before it get's send to the API.
I found a solution to the problem. In the buildPostRequest() method I changed from a StringEntity to a ByteArrayEntity and coverted the string to UTF-8 bytes.
ByteArrayEntity params = new ByteArrayEntity(json.getBytes("UTF-8"));
If I send special characters to the API the request isn't empty anymore.
try this way
HttpPost request = new HttpPost(URLEncoder.encode("url here", "UTF-8"));

Java get latest GitHub release

I had tried to acess to GitHub via Java to get the latest release of a repository and I had found this and I tried to use it with this code:
String url = "https://github.com/:owner/:repo/releases/latest";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
request.addHeader("content-type", "application/json");
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
and the only thing I get as response is the HTML code of the website but I want the json response like you can see in the exaple response here.
Thanks for the Help!
Yea, it is right, you have to acess to api.github.com and you have to set Accept: application/vnd.github.v3+json

Embedding a File Attachment in JSON Object

Is it possible to embed a file attachment in a JSON Object. I have a HTML Form, which has several text field inputs and a file attachment. I want to send a JSON Object wrapping all these form data (including the file attachment) to the server.
Are there any particular libraries in Java available to do that? Can you give possible solution for this.
Thanks
If you want to send the actual data of the file, you'd probably want to encode it as a base64 string and send that in your JSON - see fiddle for example of encoding it in javascript:
http://jsfiddle.net/eliseosoto/JHQnk/
Then you could do the opposite on your server-side using whatever language and/or libraries are appropriate.
Use MultipartEntity, someone else posted a similar question: How to send file in JSON on android?
You could also consider saving the files on the server and sending a path/url to the file location where the other server can access them.
public String SendToServer(String aUrl,File Filename)
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(filename);
try
{
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(Filename));
entity.addPart("video-title", new StringBody("Video"));
entity.addPart("video-type", new StringBody("1"));
httpPost.setEntity(entity);
HttpContext context = new BasicHttpContext();
// Bind custom cookie store to the local context
context.setAttribute(ClientContext.COOKIE_STORE, Globals.sessionCookie);
HttpResponse response = httpClient.execute(httpPost, context);
HttpEntity resEntity = response.getEntity();
String Response = "";
if (response != null)
{
Response = EntityUtils.toString(resEntity);
}
return Response;
}
catch (IOException e)
{
e.printStackTrace();
}
return "Exception";
}

calling asp webservice not working as i need

I'm trying to send user and pass to asp webservice , but when getting back response get like this :
so how to fix it and get true of false
this is webservice link i have used :
http://ictfox.com/demo/Hafil_Updates/Login_Check.aspx?UserLogin=Demo&Password=Demo
02-20 19:57:23.326: D/Http Response:(4007): True<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title></title></head><body> <form name="form1" method="post" action="Login_Check.aspx?UserLogin=Demo&Password=Demo" id="form1"><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZD/N053U40olll80mNvY/Qt2aBEc" /> <div> </div> </form></body></html>
this is my full class in asyncTask android :
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://ictfox.com/demo/Hafil_Updates/Login_Check.aspx?UserLogin=Demo&Password=Demo");
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("UserLogin", "Demo"));
nameValuePair.add(new BasicNameValuePair("Password",
"Demo"));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
response.getEntity().getContentLength();
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
catch (IOException e) { e.printStackTrace(); }
catch (Exception e) { e.printStackTrace(); }
Log.d("Http Response:", sb.toString());
Is that webservice from you or a 3dr party? It seems that it not only returns the actual return value, but also some hidden HTML stuff. Check if there is an option to call the service in a way that it returns only the desired value or even better JSON. If not, just check if the return String starts with "True"
boolean success = sb.toString().toLowerCase().startsWith("true");
You would need to modify the response sent by the server, that would be the easiest thing to do. I see that you server returns True followed by some HTML code. Make your server remove the HTML
If you don't want to modify the server side code, just look in your response for the substring True.
Additionally, to get the response I use this, which may be simpler:
httpresponse = httpclient.execute(httppost);
response = EntityUtils.toString(httpresponse.getEntity());

servlet response to android device

I am in a ditch since last few days trying out to get this,but not able to bring out any desired results.I will try to make myself clear that what i am looking for in following points:
I am working on android app,that will update the location of the user on the server using servlets(on my localhost).There is no problem regarding this,all is working fine.
The real problem that came in my way was when i was trying to get response from server back to android device,i just want to return a simple string,or something like that,Most likely a parameter,that will be utilized by the android app.Then i came to know about the json thing that i have to use it for doing what i am looking for.I have searched a lot about it,found some code too,but not able to use it well,
So my questions are
Is it possible to retrieve response from the servlet,and extract the required values from it without using json or any parsing technique,because i needed something like a single string only.
HttpClient client=new DefaultHttpClient();
HttpGet request=new HttpGet();
URI address=new URI("http://xxx.xxx.xxx.xxx:8080/MyServlet");
request.setUri(address);
HttpResponse response=client.execute(request);
The code from the android device requesting the response and the servlet are shown above,however when i call the toString method on response.toString() in android device,it yield me a string with some sequence of numbers,which are of no use to me.
HELP! HELP! HELP!
A simple example of it might help me up,
You could use a servlet that generates plain text result without any encoding technique.
On the server side, just replace your doGet function to look like that:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
On the client side, you could use the following code:
try {
final HttpClient httpClient = new DefaultHttpClient();
final HttpGet httpGet = new HttpGet("http://SERVLET_URL/");
HttpResponse response = httpClient.execute(httpGet);
final HttpEntity entity = response.getEntity();
Log.i(TAG, "Servlet Result: " + EntityUtils.toString(entity));
} catch (ClientProtocolException e) {
Log.e(TAG, "ClientProtocolException", e);
} catch (ParseException e) {
Log.e(TAG, "ParseException", e);
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}

Categories