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;
}
Related
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);
}
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());
I have run into a very strange problem and I don't have the slightest idea where to start.
I am sending a http request to a server and get a simple string as response. This worked fine in my smartphone app; it even works fine in my browser. However, while I thought I'd simply copy-and-pasted the smartphone code, it doesn't work for my tablet (Android 3.0.1) version of the app anymore.
I have checked with the debugger and the old version gets a string with a length of 2958 characters. The new version only gets a string of the length 1334, though. I've logged the URL of the new version, put it into my browser and got a string of 2985 characters again.
I really can't find any major difference in my code (please see below). Also, I can't believe there was some change in Android that would limit string length?!
So does anybody have an idea?
Original Smartphone code:
if (CheckInternet())
{
myURL = new URL(params[0]);
httpClient = AndroidHttpClient.newInstance("android");
if (rtype == RequestType.GET)
{
httpRequest = new HttpGet(myURL.toExternalForm());
}
else
{
httpRequest = new HttpPost(myURL.toExternalForm());
HttpEntity myEntity = new StringEntity(message, "UTF-8");
((HttpPost) httpRequest).setEntity(myEntity);
}
HttpParams httpParams = new BasicHttpParams();
HttpProtocolParams.setHttpElementCharset(httpParams, "UTF-8");
HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
HttpConnectionParams.setSoTimeout(httpParams, timeout);
httpRequest.setParams(httpParams);
response = httpClient.execute(httpRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 300 || statusCode >= 305)
{
errorMessage = getStatusCodeMessage(statusCode, act);
}
else
{
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line);
result = sb.toString();
}
}
}
Code in the new Tablet version:
if (CheckInternet())
{
if (isCancelled()) return null; //that's for an AsyncTask
URL myURL = new URL(params[0]);
httpClient = AndroidHttpClient.newInstance("android");
if (isCancelled()) return null;
if (params[1] == null)
{
httpRequest = new HttpGet(myURL.toExternalForm());
}
else
{
httpRequest = new HttpPost(myURL.toExternalForm());
HttpEntity myEntity = new StringEntity(params[1], "UTF-8");
((HttpPost) httpRequest).setEntity(myEntity);
}
httpRequest.setParams(httpParams);
if (isCancelled()) return null;
HttpResponse response = httpClient.execute(httpRequest);
httpClient.close();
if (isCancelled()) return null;
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 300 || statusCode >= 305)
{
error = HttpHelper.getStatusCodeMessage(statusCode, getActivity());
}
else
{
if (isCancelled()) return null;
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line);
String test = sb.toString(); //that was for debugging the string
return test;
}
}
}
Both requests are running in an AsyncTask.
Kind regards,
jellyfish
I'm not sure this is the cause, but it looks suspicious -
HttpResponse response = httpClient.execute(httpRequest);
httpClient.close(); // <--
I'd wait until after consuming the HttpEntity before closing the client.
I am new to this myself, so please forgive me if I sound like an idiot.
I found an interesting point in this article:
http://android-developers.blogspot.com/2010/12/new-gingerbread-api-strictmode.html
It said "you should never do network requests on your main thread. In fact, in the upcoming Honeycomb release we’ve made network requests on the main thread a fatal error, unless your app is targeting an API version before Honeycomb"
Are you running your request in a separate ASyncThread? I cant tell by looking at the code. I am having a doozie of a time doing this myself. Please let me know if you come up with anything, as I would LOVE to see how you did it.
Sincerely,
Andrew
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