Json Parse not working properly but works on jsontest - java

I am a new programmer, i am trying to build an app with Json.
I created Json parser class and in my main activity i have the following code :
String url = "http://echo.jsontest.com/key/value/one/two";
JSONObject json = jParser.getJSONFromUrl(url);
one = json.getString(gridArray.get(lekeres).getTitle()); // one has the good value "two"
This works great. BUT
if i change url to : https://api.myjson.com/bins/3f8d2
which is exactly the same code as in the jsontest, one doesn't have "two" . I searched for hours but i don't know why this is happening. I did nothing but change the url. The contest is the same...

Since I don't know how is your parser. I made a quick test and can read both link normally with this code:
try {
//url = new URL(""http://echo.jsontest.com/key/value/one/two2");
url = new URL("https://api.myjson.com/bins/3f8d2");
InputStream is = url.openStream();
JSONObject json = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
String jsonText = sb.toString();
json = new JSONObject(jsonText);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This is more examples: http://en.proft.me/2013/12/5/how-parse-json-java/.
You can make your getJSONFromUrl similarly. Otherwise like other suggest try without https://.

Related

I cant insert data from a java program to laravel app via api

I am new to laravel and I would like to save data to my online server via laravel api from a java program but I am getting errors.
this is my route on api.php:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('hooks','ApiTestController#store');
my ApiTestController: its just handles POST request then saves to the table.
public function store(Request $request)
{
$postdata = json_decode($request->input('post_data'), true);
$datas = $postdata['header'];
$data = $datas[0];
$testH = new TestH();
$testH->test_date = $data['test_date'];
$testH->expiration = $data['test_date'];
$testH->source = $data['source'];
$testH->save();
return $testH;
}
and my java code :
try {
//local development server url
URL url = new URL("http://127.0.0.1:8000/api/hooks");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
//create the JSON String
String json = null;
StringWriter sw = new StringWriter();
JSONWriter wr = new JSONWriter(sw);
try {
wr.object().key("header").array();
wr.object();
wr.key("test_date").value(new Date());
wr.key("source").value("TEST");
wr.key("expiration").value(new Date());
wr.endObject();
wr.endArray().endObject();
json = sw.toString();
System.out.println(json);
} catch (JSONException ex) {
Logger.getLogger(WebConnectSample.class.getName()).log(Level.SEVERE, null, ex);
}
// send to laravel server
ps.print("post_data="+json);
HttpURLConnection httpConn = (HttpURLConnection) con;
InputStream is;
if (httpConn.getResponseCode() >= 419) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
// read the server reply
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
// close the print stream
}
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
the thing is when I dont save via $testH->save() everything works fine. but if I include it java returns with the following error:
Type error: Argument 1 passed to Illuminate\Routing\Middleware\ThrottleRequests::addHeaders() must be an instance of Symfony\Component\HttpFoundation\Response, string given, called in C:\Users\relixusdev\Documents\WebProjects\tcmsite\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php on line 61
any idea what part causes the error? does it have to do with authentication? i just want to be able to save to the online database via my java program.
Try using Route group with prefix as below
Route::group(['prefix' => 'api'], function() {
Route::post('hooks','ApiTestController#store');
});
if anyone comes here having the same problem, i found out that the problem is that I dont have the created_at and updated_at column at my table. I didn't realized its a requirement for laravel. silly me.

Issue with Retrieving JSON from Webpage Android

So I'm facing some difficulty in trying to, what seems simply, obtain a JSON file from a webpage, and then parse it on Android. I have already built the parser, and tested it in Eclipse (in fact, all of the code works in Eclipse). However, when I run the HttpURLConnection and try to retrieve the JSON data in a string in Android Studio, I end up getting no exceptions and an almost empty string (I think I am getting the 1st, 2nd, 3rd, and last character, but not too sure). I have included parts of the code below, and
URL url = null;
HttpURLConnection urc = null;
try {
url = new URL(query);
urc = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urc.getInputStream());
jsoncontent = readStream(in);
System.out.println(jsoncontent);
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
urc.disconnect();
}
The code for readStream() is below
private static String readStream(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(is),1000);
for (String line = r.readLine(); line != null; line =r.readLine()){
sb.append(line);
}
is.close();
return sb.toString();
}
Here is an exact chunk from an assignment I did last semester:
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "text/html");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
JSONObject searchResults = new JSONObject(in.readLine());
...
conn.disconnect();
You seem to be missing setRequestMethod("GET") and setRequestProperty("Accept", "text/html") in your code. Hope this helps.

Android: BufferedReader returns wrong data after second time

I am working on an android app which uses AsyncTasks in order to get JSON data from an applications API. When I start my app, everything goes well and the app gets the right information out of the API.
I implemented ActionBar pull-to-refresh library so people can drag down my listview to refresh their data. Now my app crashes on this point.
Instead of receiving any text, my BufferedReader.readline returns strings like this.
���ĥS��Zis�8�+(m��L�ޔ�i}�l�V�8��$AI0��(YN�o�lI�,9cO�V͇� $��F���f~4r֧D4>�?4b�Տ��P#��|xK#h�����`�4#H,+Q�7��L�
Everytime my app wants to receive data, a new AsyncTask will be created so I don't know why my reader returns something like that...
I hope you guys can give me any idea on how to fix this!
EDIT: This is how I get my data.
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
} catch (IOException e1) {
e1.printStackTrace();
}
String s = null;
String data = "";
try {
while ((s = reader.readLine()) != null)
{
data += s;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I just had the same issue. I found out that the returned HTML might be compressed into a GZIP format. Use something like this to check for encoding, and use the appropriate streams to decode the content:
URL urlObj = new URL(url);
URLConnection conn = urlObj.openConnection();
String encoding = conn.getContentEncoding();
InputStream is = conn.getInputStream();
InputStreamReader isr = null;
if (encoding != null && encoding.equals("gzip")) {
isr = new InputStreamReader(new GZIPInputStream(is));
} else {
isr = new InputStreamReader(is);
}
reader = new BufferedReader(isr);
And so forth.
Have you tested other enconding like BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
You can check all the avaliable encondings on this web page enconding.doc

How to get VIEWSTATE before posting using HttpURLConnection (android/java)?

I am writing an Android application, and have been looking for a way to get the _VIEWSTATE from the server I want to post to so I can put it in my Http post content. A few people recommended regex, but then some other pros were strongly opposed to parsing HTML with regex. So, how to parse the _VIEWSTATE ? I am using HttpURLConnection/HttpsURLConnection in an AsyncTask. Also, don't I need to put the InputStream reader first, to get the _VIEWSTATE first? All the android examples put the input stream after the output stream. Here is what my code looks like so far (posting to one site that has three pages that have to be "clicked through"):
In my Activity, I call the Async task like this:
//execute AsyncTask for all three reports
submit_report.execute(report1, report2, report3);
My Async task doInBackground method:
class UploadReportTask extends AsyncTask<HashMap<String,String>, ProgressBar, Void> {
//this is called on task.execute
protected Void doInBackground(HashMap<String,String>...maps) {
System.out.println("Report is being uploaded");
URL url = null;
try {
url = new URL(getString(R.string.url_dnc));
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept-Charset", utf);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + utf);
urlConnection.setChunkedStreamingMode(0);
//For each map in maps, encode the map,
//get the headers, add the headers to the map, convert to bytes,
//then post the bytes,
//get response.
for (HashMap<String,String> map : maps){
byte[] payload = makePayload(map);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
//urlConn.connect //I think this happens here
out.write(payload);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int length = in.read();
String result, line = reader.readLine();
result = line;
while (length != -1){
result+=line;
}
System.out.println(result);
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
finally{
urlConnection.disconnect();
}
return null;
}
protected String parseViewstate(String response){
int i = 0;
String viewstate = "";
while (true){
int found = response.indexOf("\"__VIEWSTATE\"", i);
if (found == -1) break;
int start = found + 38; //check numbers from start of "__V"
int end = (response.indexOf("/>", start)) -2;
viewstate = response.substring(start, end);
i = end + 1;
}return viewstate;
}

Grabbing JSON works from one link, not from another

I'm doing a simple JSON grab from two links with the same code. I'm doing it two separate times, so the cause of my issue isn't because they're running into each other or something.
Here is my code:
#Override
protected String doInBackground(Object... params) {
try {
URL weatherUrl = new URL("my url goes here");
HttpURLConnection connection = (HttpURLConnection) weatherUrl
.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
Log.v("test", responseData);
When I try this with:
http://www.google.com/calendar/feeds/developer-calendar#google.com/public/full?alt=json
I get an error of having an array lenth of -1
For this link:
http://api.openweathermap.org/data/2.5/weather?id=5815135
It returns fine and I get a log of all of the JSON. Does anyone have any idea why?
Note: I tried stepping through my code in debug mode, but I couldn't catch anything. I also downloaded a Google chrome extension for parsing json in the browser and both urls look completely valid. I'm out of ideas.
Log this: int contentLength = connection.getContentLength();
I don't see the google url returning a content-length header.
If you just want String output from a url, you can use Scanner and URL like so:
Scanner s = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\\A");
out = s.next();
s.close();
(don't forget try/finally block and exception handling)
The longer way (which allows for progress reporting and such):
String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
} catch (IOException e) {
// Handle exception
} finally {
try {
is.close();
} catch (IOException e) {
// Handle exception
}
}
return sb.toString();
}
}
and then call String response = convertStreamToString( inputStream );

Categories