I'm trying to get XML content from an URL:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://www.domain.com/test.aspx"));
HttpResponse response = client.execute(request);
in = response.getEntity().getContent();
When I write out the response content, this is truncated before the end of the content.
Any idea?
Did you use a InputStreamReader for the input stream in?
String s = "";
String line = "";
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
try {
while ((line = rd.readLine()) != null) { s += line; }
} catch (IOException e) {
// Handle error
}
// s should be the complete string
maybe i have solved, was the android emulator. Simply restarting it all works fine.
Thanks to all
Related
This is my code. I am receiving HTTP/1.1 400 Bad Request. Not sure if I did something wrong here.
try {
//client = new DefaultHttpClient();
client=HttpClientBuilder.create().build();
get = new HttpGet(queryURL.toString());
HttpResponse response = client.execute(get);
if(HttpStatus.SC_OK!=response.getStatusLine().getStatusCode()) {
throw new ServiceException(this, response.getStatusLine().getStatusCode()+"", response.getStatusLine().toString());
}
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuffer json = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
json.append(line);
}
The error message.
ServiceException: HTTP/1.1 400 Bad Request
To find out reason of the Bad Request firstly you should see the response text. You can write as following:
client=HttpClientBuilder.create().build();
get = new HttpGet(queryURL.toString());
HttpResponse response = client.execute(get);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder responseAsString = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
responseAsString.append(line);
}
if(HttpStatus.SC_OK!=response.getStatusLine().getStatusCode()) {
throw new ServiceException(this, response.getStatusLine().getStatusCode()+"", response.getStatusLine().toString() + ", cause: " + responseAsString);
}
I do not know what I am doing wrong, but I cannot access a REST API using the POST method in Java with Json parameters.
Each time I run the program, I receive Java.net.SocketException - Connection Reset.
I tried to access the API from PHP, and it worked.
Code: https://github.com/BobTheProgrammer/Question/blob/master/POST
try this one
public static void HttpPost() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://api.website.net/auth/token");
StringEntity input = new StringEntity("{\"auth\":{\"user\":{\"id\":\"bla\",\"password\":\"bla\"}\"method\":\"user\",\"website\":\"http://website.net/\"}}");
post.setEntity(input);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
There is a problem with the JSON syntax in your source code in line number 55, you have missed a comma after the user object.
Replace this line
String urlParameters = "{\"auth\":{\"user\":{\"id\":\"bla\",\"password\":\"bla\"}\"method\":\"user\",\"website\":\"http://website.net/\"}}";
with this one(added a comma after the user object before method)
String urlParameters = "{\"auth\":{\"user\":{\"id\":\"bla\",\"password\":\"bla\"},\"method\":\"user\",\"website\":\"http://website.net/\"}}";
im having a strange problem when receiving json results from the server. I have no idea what the problem is. The thing is that my String json result is corrupted, with strange symbols.
The result is like this (taken from eclipse debug)
Image :
Another strange thing that happens is that when I change the URL of the service to an alternative one, it works and the data is not corrupted. The URLs are the same but once redirects everything to the other.
The URL is use always is (example) http://www.hello.com
The URL that works is http://www.hello.com.uy
(cant post the exact link for security reasons)
The second one redirects everything to the first one, its the only thing it does.
I have tried changing the encoding to UTF-8 and it is still not working, here is the code (with one of the URLs commented)
I have also tried using Dev HTTP Client extension from chrome to check the service and it works fine, no corrupted data. Also, it works perfectly on iOS so i think its just and android/java issue.
DevClient:
try {
JSONObject json = new JSONObject();
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
//String url = TAG_BASEURL_REST +"Sucursal";
String url = "http://www.-------.com/rest/Sucursal";
//String url = "http://www.--------.com.uy/rest/Sucursal";
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String jsonRes = sb.toString();
JSONArray jObj = new JSONArray(jsonRes);
return jObj;
}
} catch (Throwable t) {
Log.i("Error", "Request failed: " + t.toString(), t);
}
return null;
InputStream is = entity.getContent();
// check if the response is gzipped
Header encoding = response.getFirstHeader("Content-Encoding");
if (encoding != null && encoding.getValue().equals("gzip")) {
is = new GZIPInputStream(is);
}
My code to get image Urls
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
inputStream.close();
return stringBuilder.toString();
where server code is in php
But problem is there is extra \ before every /
e.g. in database image Url is, http://www.dvimaytech.com/markphoto/upload/herwadeshirish123#Gmail.com/Pic.jpg
but I get every time http:\/\/www.dvimaytech.com\/markphoto\/upload\/herwadeshirish123#Gmail.com\/Pic.jpg
Is this problem isn't solvable, then another solution(its last option for me) is to remove every .
But when I try that using url = url.replace("\","");
it gives syntax error String literal is not properly closed by a double-quote
Just use a JSON parser library like gson to decode your JSON packets for you.
http://code.google.com/p/google-gson/
It will make your life much easier and avoid having to string.replace() specific characters.
You can use the following method to handle that
public static String extractFileName(String path) {
if (path == null) {
return null;
}
String newpath = path.replace('\\', '/');
int start = newpath.lastIndexOf("/");
if (start == -1) {
start = 0;
} else {
start = start + 1;
}
String pageName = newpath.substring(start, newpath.length());
return pageName;
}
So I'm building an URL to be called to get a JSON response but facing a strange issue. Building the URL as shown below returns "Not found" but for testing purposes I just built the URL as such "http://api.themoviedb.org/3/search/person?api_key=XXX&query=brad" and didn't append anything and that returned the correct response. Also tried not encoding "text" and same thing...Not found. Any ideas?
StringBuilder url = new StringBuilder();
url.append("http://api.themoviedb.org/3/search/person?api_key=XXX&query=").append(URLEncoder.encode(text, ENCODING));
Log.v("URL", url.toString());
try {
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream input = bufHttpEntity.getContent();
String result = toString(input);
//JSONObject json = new JSONObject(result);
return result;
Try using the code I have below. I've copied and pasted it out of some code I use and I know it works. May not solve your problem but I think its worth a shot. I've edited it a little bit and it should just be copy and paste into your code now.
HttpGet request = new HttpGet(new URI(url.toString()));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONObject jResponse = new JSONObject(builder.toString());