Reading JSON content from Android - android

I'm having issue with reading JSON from URL.
For desktop applications I have been using "curl" to read content from URL.
i.e. curl -H 'Accept: application/json' 'http://example.com/abc.py/data'
I am using following code to do the same in Android App but it is not working.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Accept", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Can anyone help with this?
Thanks,

There are many reasons it might not work, one reasons is that it is actually inputStream that's returned by getContent, here's a snippet of working code from my app
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
...
private static String getInputStreamAsString(Context ctxt, InputStream is)
{
byte[] sBuffer = new byte[512];
ByteArrayOutputStream content = new ByteArrayOutputStream();
// Read response into a buffered stream
int readBytes = 0;
try
{
while ((readBytes = is.read(sBuffer)) != -1)
{
content.write(sBuffer, 0, readBytes);
}
}
catch (IOException e)
{
Util.e(ctxt, TAG, Util.fmt(e));
}
return new String(content.toByteArray());
}
public static test() {
HttpClient client = DefaultHttpClient()
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);;
StatusLine status = response.getStatusLine();
String str = getInputStreamAsString(ctxt, response.getEntity().getContent());
JSONObject json = new JSONObject(str);
}
...

Thank you all for your replies.
The error was occurring because I didn't set Internet permission within manifest so it wasn't able to connect to the URL.
It works now :)

Related

Http Authentication via Android

I currently try to make an authentication on Android the same way I'm doing it with Postman here.
I followed some examples everywhere on the Internet and I came up with this code :
protected String doInBackground(Void... voids) {
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("_username", mylogin));
nameValuePairs.add(new BasicNameValuePair("_password", mypassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = client.execute(httppost);
StatusLine status = response.getStatusLine();
if (response.getStatusLine().getStatusCode() != 200) {
throw new Exception("Status Error CODE : " + status.getStatusCode());
}
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int readCount;
while ((readCount = in.read(buff)) != -1)
{
out.write(buff, 0, readCount);
}
return new String (out.toByteArray());
}catch (Exception e){
e.printStackTrace();
}
return null;
}
I keep getting an Error 401 and I don't understand why. Is there anything that I'm not seeing ?
By the way I also try to use its method but didn't get better.
Thanks for helping me !
Find the solution, the problem wasn't from Android but from the server under Symphony. Symphony needed to create a session before accepting requests.

JSON merge two responses in android

I am using JSON to get response from my server.
This is code:
HttpClient httpclient = new DefaultHttpClient();
HttpClient httpclient2 = new DefaultHttpClient();
HttpResponse response;
HttpResponse response2;
try {
HttpGet request = new HttpGet(GlobalConfig.getMagazineUrl());
HttpGet request2 = new HttpGet(GlobalConfig.getMagazinePagesUrl(1));
request.addHeader("Authorization", "Basic " + Base64.encodeToString(
(GlobalConfig.getAuthString()).getBytes(),Base64.NO_WRAP));
request2.addHeader("Authorization", "Basic " + Base64.encodeToString(
(GlobalConfig.getAuthString()).getBytes(),Base64.NO_WRAP));
response = httpclient.execute(request);
StatusLine statusLine = response.getStatusLine();
response2 = httpclient2.execute(request2);
StatusLine statusLine2 = response2.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK && statusLine2.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream out2 = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
response2.getEntity().writeTo(out2);
out.close();
out2.close();
return parser(out.toString(), out2.toString());
As you can see in parser(out.toString(), out2.toString()) I return both responses as String. I would like to know how I can merge this two JSON responses in one. I don't want to merge two strings, I need merge two JSON respons in one big response. This is possible? If yes how I can do that?
Perhaps thats what you want:
...
JSONObject json = new JSONObject();
json.put("response1", new JSONObject(out.toString()));
json.put("response2", new JSONObject(out2.toString()));
Now return either json.toString() or json depending on the return type.

Android BufferedInputStream HTTP POST/GET

I Use BufferedInputStream For HTTP POST/GET
But I Get Some Error the Below
java.io.FileNotFoundException: http://XX.XX.XX.XX/WebWS/data.aspx
Transport endpoint is not connected
Why Get This Error. My Code is Below
URL url = new URL(glob.postUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
try {
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Language", "TR");
httpConn.setConnectTimeout(12000);
Iterator<String> reqProps = hMap.keySet().iterator();
while (reqProps.hasNext()) {
String key = reqProps.next();
String value = hMap.get(key);
httpConn.addRequestProperty(key, value);
}
InputStream in = new BufferedInputStream(httpConn.getInputStream());
StringBuilder builder = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} finally {
in.close();
}
httpConn.disconnect();
Thanks.
Is there any reason you're not using HttpClient?
You can replace your code with something like:
HttpContext httpContext = new BasicHttpContext();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet, httpContext);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String page = EntityUtils.toString(entity);
You can setup the HttpClient with ClientConnectionManager and HttpParams for security and various http parameters for the client at initialisation (plenty of examples around if you search on class names).
HttpURLConnectionImpl.getInputStream() is known to throw a FileNotFoundException if the HTTP response status code is 400 or higher, i.e. for any error condition on the server side. You should check what the status code really is in order to obtain suitable debug information.
However, I second Mark Fisher's suggestion about using HttpClient, which AFAIK is the preferred way of working with HTTP on Android.

Error using HTTP Post

I got an error using HttpPost for sending an MMS in Android.
In the Logcat it says:
ERROR/Here(447): ---------Error-----Target host must not be null, or set in parameters.
My sample code:
String url = "myurl";
HttpClient httpClient = new DefaultHttpClient();
try {
httpClient.getParams().setParameter(url, new Integer(90000)); // 90 second
HttpPost post = new HttpPost(url);
File SDCard = Environment.getExternalStorageDirectory();
File file = new File(SDCard, "1.png");
FileEntity entity;
entity = new FileEntity(file,"binary/octet-stream");
entity.setChunked(true);
post.setEntity(entity);
post.addHeader("Header", "UniqueName");
Log.i("MMSHTTP","----post---------------"+post);
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Log.e("Here",
"--------Error--------Response Status line code:" + response.getStatusLine());
}
else
{
// Here every thing is fine.
}
HttpEntity resEntity = response.getEntity();
if (resEntity == null) {
Log.e("Here","---------Error No Response!!-----");
}
} catch (Exception ex) {
Log.e("Here","---------Error-----"+ex.getMessage());
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
How do I fix the error?
The url you're specifying is in your sample code is:
String url = "myurl";
In order for HttpClient to be able to determine the host name, you're going to need to supply a valid url. Something along the lines of:
String url = "http://myurl.com/index";
Note: The 'http://' is important so that the appropriate protocol can be determined.
This guy had the same problem.

Android - image upload sending no content

I've been looking into this for the last day or two and can not seem to find a solution to my issue. I am trying to post an image to a server using httppost.
I have tried two ways of doing this and both complete the post but with no content i.e. the content length is 0.
The first is as follows:
String url = "MYURL";
HttpClient httpClient = new DefaultHttpClient();
try {
httpClient.getParams().setParameter("http.socket.timeout", new Integer(90000)); // 90 second
HttpPost post = new HttpPost(url);
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"/DCIM/100MSDCF/DSC00004.jpg");
FileEntity entity;
entity = new FileEntity(file,"binary/octet-stream");
entity.setChunked(true);
post.setEntity(entity);
post.addHeader("Header", "UniqueName");
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Log.e("Here","--------Error--------Response Status line code:"+response.getStatusLine());
}else {
// Here every thing is fine.
}
HttpEntity resEntity = response.getEntity();
if (resEntity == null) {
Log.e("Here","---------Error No Response!!-----");
}
} catch (Exception ex) {
Log.e("Here","---------Error-----"+ex.getMessage());
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
and the second is:
String url = "MYURL";
//File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(Environment.getExternalStorageDirectory(),"/DCIM/100MSDCF/DSC00004.jpg");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
// Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Log.d("finishing", "The try catch function");
} catch (Exception e) {
// show error
}*/
As you can see I have hardcoded a path to a specific image, this is to be dynamic when I get it up and running.
Can anyone see what i'm doing wrong? Am I leaving out something? I know I use setChunked and setContenttype - is there a setContent option?
Any help would be grately appreciated.
Thanks,
jr83.
You can use upload your image by sending multipart messages; you might find this discussion useful.

Categories

Resources