The most basic HttpGet request on Java - java

I need help performing a RESTful call to a website that returns a JSON object. I'm stuck with the options that are available but I would prefer to use something that comes right out of the box and not install any third party plugins.
Here's what I currently have so far:
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://search.twitter.com/search.json?q=%40apple");
HttpResponse httpResponse = httpClient.execute(httpGetRequest);
I know that the URL used in this example returns the following:
{"errors":[{"message":"The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.","code":64}]}
Which is fine by me, I just want to at least convert the JSON response into a string so that I can move on from here. I'm very familiar to how REST works and it's been pretty easy to get it working on Objective-C and Python but Java for some reason has a dozen implementations for getting it to work properly, I'm just looking for the most basic approach possible, I'm not doing anything crazy like uploading images to a server.
So the issue with my code above is that I'm getting a ClientProtocolException error and the httpClient.execute() requires a try catch statement, this is something brand new to me, I've never had a compiler yell at me for not inserting try catch statements.
How can I fix this to call a url that converts a very basic JSON object to a string?

This code should work:
try {
HttpResponse response;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getConnection = new HttpGet(url);
try {
response = httpClient.execute(getConnection);
String JSONString = EntityUtils.toString(response.getEntity(),
"UTF-8");
JSONObject jsonObject = new JSONObject(JSONString); //Assuming it's a JSON Object
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}

Related

Parsing extremely simple JSON from a URL in in Android

I have tried everything online to try to parse this JSON but nothing seems to work. Here is the JSON:
{"salonphoebe":true,"salonvo":false}
That's it. It is only booleans. It is from an HTTP website if that is important at all.
How do I do parse this extremely simple JSON from http://example.com in Java in Android Studio? I am trying to create Booleans based on these in my app. I know this question is on this website a lot but I have literally tried 10 solutions but nothing will work. Thank you.
Try the following code.
try {
JSONObject json = new JSONObject(your - json - string - here);
boolean b1 = json.optBoolean("salonphoebe");
boolean b2 = json.optBoolean("salonvo");
} catch (JSONException e) {
e.printStackTrace();
}
Okay I have solved my own problem. Here is everything I learned and what I did. I want to help anyone else with this problem if they come across this issue. First I added this to my androidmanifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Then I added this between the tags in the androidmanifest.xml beucase the link I am parsing the JSON from is an HTTP link:
android:usesCleartextTraffic="true"
Really quickly import all of this into your mainactiviy.java:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
Then we get into the hard stuff. There are two parts to parsing JSON data from the internet. First, you must read the JSON (meaning put the JSON from online into a String) from the URL and then you must organize the String of JSON into separate variables. So let's start on the HTTP Request. I created an Async class in my MainActivity.java (under the OnCreate) that I found online that looks like this:
public class HttpGetRequest extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String url = "http://example.com/example.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
System.out.println("Test");
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String jsonResponse = response.toString();
return jsonResponse;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json = new JSONObject(result);
boolean myJsonBool = json.optBoolean("samplestringinyourjson");
if(hasPaid){
//do something
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Okay so basically the reason we put this in an Async class is because java won't let you make an HTTP Request in your OnCreate. What the doInBackground is doing is fetching the JSON data and putting it into the string like I said. The OnPostExecute is separating that string into boolean values and doing stuff with it. Lastly, paste this into your OnCreate or it won't work:
new HttpGetRequest().execute();
That's it. If you have questions ask and hopefully I can see it.

When accessing SQL DB from android device, my httpEntity is returning null, can anyone inform me as to why this is?

This my connector class that should call on the php script to access the database. When debugging I find that httpEntity is returning null therefore not detecting any results from the database. The url works fine in the browser so im not sure whether or not this is the issue.
import android.os.StrictMode;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
public class ApiConnector {
public JSONArray GetAllCustomers()
{
// URL for getting all customers
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String url = "mydburl";
// Get HttpResponse Object from url.
// Get HttpEntity from Http Response Object
HttpEntity httpEntity = null;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.v("response code", httpResponse.getStatusLine()
.getStatusCode() + "");
httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
// Signals error in http protocol
e.printStackTrace();
//Log Errors Here
} catch (IOException e) {
e.printStackTrace();
}
// Convert HttpEntity into JSON Array
JSONArray jsonArray = null;
if (httpEntity != null) {
try {
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response : ", entityResponse);
jsonArray = new JSONArray(entityResponse);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonArray;
}
}
php Script (works in browser)
<?php
$con = $con = mysql_connect("localhost","root","");
// Check connection
if (!$con)
{
echo "Failed to connect to MySQL: " . mysql_error();
}
mysql_select_db("dbname", $con);
$sql = 'SELECT * FROM `locations` ';
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>
There was in fact two problems here, the first was to do with my php script, once i modified it to run mysqli instead of my sql it ran correctly.
Another was to do with the ip address i was passing through, the device was trying to read from the localhost from my device rather than the localhost of my laptop. To fix this i entered my ipv4 address.

Using Java with SleepyMongoose to perform MongoDB inserts

this is my first post here.
In a nutshell, I've set up a MongoDB instance, and installed a REST service to run commands on it. The one I chose was SleepyMongoose.
I've been trying to write a simple Java program to do three things: a find, an insert, and another find. Basically, display the collection, insert something, and display it again to show the update. The finds work correctly, but the insert has been giving me trouble.
The documentation of SleepyMongoose uses curl with a data parameter, but I've been using Java's HttpURLConnection. How can I add that data parameter to the HttpURLConnection? Here's what I've been trying:
private static void POST (String command) {
try {
// The 'command' is just going to be 'insert' for now.
URL restURL = new URL(REST + DATABASE + "/" + COLLECTION + "/_" + command);
HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.connect();
OutputStream out = conn.getOutputStream();
String x = "docs=[{'x':1}]";
out.write(x.getBytes());
out.close();
conn.disconnect();
}
catch (Exception e) {
System.out.println("Uh oh...");
e.printStackTrace();
}
}
Am I even using SleepyMongoose for its correct purpose? Are there better alternatives? I'm not tied down to any REST api, but I'd like to get the inserts down.
Thanks everyone
For some reason, it only works if there's a reader attached to it, too. If I attach the following immediately after the write, it works perfectly:
String line, output = "";
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null)
output += line;
rd.close();
Can someone explain this?
I happen to be writing similar code for an Android project and have had success with the below when doing a POST.
Note that the data you get back will need to be parsed as it comes in as a HttpResponse. I have been converting it to a String then pulling out JSON values (see below).
Sample insert:
String[] link2 = {"http://XXX.XXX.XXX.XXX:27080/foo/bar/_insert", "[{\"x\":2},{\"x\":3}]"};
new HTTPPost().execute(link2);
Code for POST, yours will be different due to not writing for Android specifically. Replace AndroidHttpClient with HttpClient. Note the BasicNameValuePair used to specify "docs" as key.
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
protected HttpResponse doInBackground(String... params) {
String link = params[0];
String value = params[1];
HttpPost post = new HttpPost(link);
AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("docs", value));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
return client.execute(post);
} catch (IOException e) {
return null;
} finally {
client.close();
}
}
To parse to string:
String test = EntityUtils.toString(result.getEntity());
To pull out JSON values:
public String parseJSON(String toParse)
{
try {
JSONObject jObject = new JSONObject(toParse);
String aJsonString = jObject.getString("ok");
JSONArray jArray = jObject.getJSONArray("results");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("link");
return oneObjectsItem;
} catch (JSONException e) {
// Oops
}
}
} catch (Exception ex) {
}
return "";
}

Source not found error after HttpClient.execute()

I am new to android development. I have the following class for downloading some data in JSON format. I keep getting a Source not found error on the
HttpResponse httpResponse = httpClient.execute(httpPost);
line... I'm sure this must be a simple fix... Here is the class code...
package com.example.tankandroid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Put this code in onCreate method
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Use Apache HttpCore and HttpClient libraries. Put these two libraries into your lib folder, its automatically add these into your build path.
One reason for this situation may be missing internet permissions in AndroidManifest.xml file. Adding this line in manifest will fix the issue.
<uses-permission android:name="android.permission.INTERNET" />
You need to provide some more information I think. Where do you get the "Source not found" error? Is it an Eclipse error that prevents you from compiling. Is it during compilation? Is it a runtime error? Could this be a possible duplicate of: Source not found Android? ?
Question: Why are you doing an HTTP POST if you don't intend to add any POST data? A GET seems more appropriate.
And since you also ask "I'm sure this must be a simple fix" then yes, it is. I'd really suggest that you rip out your HTTP code and switch to Android Asynchronous Http Client. It's super easy to work with and very well suited for getting an HTTP response and parsing it. Example:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("some_param", "some value");
rp.put("another_param", "some other value");
client.post("http://www.simonsayssolutions.co.uk/index.php", rp, new AsyncHttpResponseHandler() {
#Override
public final void onSuccess(String response) {
// handle your response and parse JSON here
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
}
});
or GET:
client.get("http://www.simonsayssolutions.co.uk/index.php", rp, new AsyncHttpResponseHandler() {
...
}
And finally if you want to simplify JSON parsing have a look at Jackson or Gson. Especially if you want to parse JSON data to Java objects and vice versa.

Getting exception near DefaultHttpClient when i am trying to access restful wcf service in java.Here is my code

Getting exception near DefaultHttpClient when i am trying to access restful wcf service in java.Here is my code:
public String rest(String SERVICE_URI){
String a="";
try{
HttpGet request = new HttpGet(SERVICE_URI + "/hello");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
**DefaultHttpClient httpClient = new DefaultHttpClient();**
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONArray plates = new JSONArray(new String(buffer));
a=plates.toString();
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return a;
}
the exception is :
Exception in thread "main" java.lang.VerifyError: (class:
org/apache/http/impl/client/DefaultHttpClient,
method: createHttpParams signature:
()Lorg/apache/http/params/HttpParams;)
Incompatible argument to function
Please can anyone help me ...Thank you.
This seems to be a class loader problem. Your code is probably compiled against one jar file (containing the HTTP client stuff). But when it's run, a different, incompatible jar file with the same class is used.
Are you running the code within an application server? If yes, the application server might already have a different version of the Apache Http client libraries in a shared location that takes precedence.
I would guess that your problem might be related to the fact that you are setting a Content-Type header for a GET. GET requests should not include Content-Type headers.

Categories

Resources