//I try to make an function for catching all results of search of some string, //but I only catching one element and my for does not continue to all results of //my search.
//There is an error in my loop sequence?
//Do you have any soggestion?
//This is my code.
//Sorry my code it is in spanish.
private void Buscar(String tema){
String url = "http://www.google.com/search?q="+tema;
String resultado;
String[] resultados;
DefaultTableModel model = (DefaultTableModel) jT_ResultadosBusqueda.getModel();
int contacampos;
try{
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
StringBuffer response = new StringBuffer();
while ((tema = in.readLine()) != null) {
response.append(tema);
}
in.close();
resultado = response.toString();
resultados = resultado.split("<a href=\"/url?q=");
contacampos = 1;
do{
for (int i = 0; i < resultados.length; i++) {
//JOptionPane.showMessageDialog(this,i);
//JOptionPane.showMessageDialog(this,resultados.length);
int inicio = resultados[i].indexOf("\"http");
//JOptionPane.showMessageDialog(this,inicio);
int fondo = resultados[i].indexOf("\">");
//JOptionPane.showMessageDialog(this,fondo);
String result = resultados[i].substring(inicio + 1, fondo);
model.addRow(new Object[]{result,"Ejemplo1","Tema1","Asunto1","www.1.com"});
}
contacampos = contacampos +1;
}while(contacampos<resultados.length);
}catch(HeadlessException | IOException e){
JOptionPane.showMessageDialog(this,e.getMessage (),"¡Aviso!",JOptionPane.ERROR_MESSAGE);
}
}
The solution it was Jsoup.
This is my actual code.
private void Buscar(String tema){
try {
// TODO add your handling code here:
org.jsoup.nodes.Document doc = Jsoup.connect("http://www.google.com/search?q="+tema).get();
DefaultTableModel model = (DefaultTableModel) jT_ResultadosBusqueda.getModel();
//doc.title()
Elements link = doc.select("a[href]");
for (Element linkline : link) {
JOptionPane.showMessageDialog(this,linkline);
model.addRow(new Object[]{linkline.tagName(),linkline.id(),"","",""});
}
} catch (IOException ex) {
Logger.getLogger(Buscador.class.getName()).log(Level.SEVERE, null, ex);
}
}
Related
public class PerformNetworkTasks extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<String>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo.toString();
/*
right now I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
inputDataTV.setText(result);
}
I need to return some data individually. So I need to return an array (i think) so that I can set the TextView as e.g. arrays.get(number).
Is there some other way that I am not realizing here, or should I continue with what I am doing to get the data individually?
Just to add, I am getting the info from a website.
You can return any data type you want
but your AsyncTask structure should be based on result data type
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>/*resultParam*/> {
#Override
protected List<String>/*will same as result parma*/ doInBackground(String... params) {
return null;/*now you can return list of string*/
}
#Override
protected void onPostExecute(List<String>/*finally receive result*/ result) {
super.onPostExecute(result);
}
}
so your code will be
public class PerformNetworkTasks extends AsyncTask<String, String, List<String>> {
#Override
protected List<String> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //getting the connection to the URL to read JSON data
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<String> allInfo = new ArrayList<>(); // list to put all the returned information
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
allInfo.add(quesnum);
allInfo.add(questype);
allInfo.add(question);
allInfo.add(ans1);
allInfo.add(ans2);
allInfo.add(ans3);
allInfo.add(ans4);
allInfo.add(correctans);
allInfo.add(category);
allInfo.add(notes);
allInfo.add(flag);
allInfo.add("\n");
}
return allInfo;
/*
right now
I am returning the list as a String,
so that I can actually view the data.
I need to put this data into their own TextViews.
So how can I return the list I have so that I can set
the individual TextViews as one section from the list?
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
inputDataTV.setText(result.get(0));
}
}
I am trying to print the data from a URL in Table but I'm only able to print the one record. I need all the records those are available
I do the following:
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Intent myNewIntent=getIntent();
URL url = null;
try {
url = new URL("http://192.168.59.1:8080/WebApplication2/cegepgim/mobile/message");
HttpURLConnection client = null;
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("GET");
int responseCode = client.getResponseCode();
System.out.println("\n Sending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
InputStreamReader myInput = new InputStreamReader(client.getInputStream());
BufferedReader in = new BufferedReader(myInput);
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("The response is " + response.toString());
JSONObject mainObject = new JSONObject(response.toString());
JSONArray jsonArray = mainObject.getJSONArray("message");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject message = jsonArray.getJSONObject(i);
message_id =""+message.getInt ("message_id");
sender_id =""+message.getInt ("sender_id");
receiver_id =""+message.getInt("receiver_id");
message_content = message.getString("message_content");
message_date = message.getString("message_date");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
tr1 = new TableRow(Main3Activity.this);
mszid = new TextView(Main3Activity.this);
mszid.setText(message_id);
tr1.addView(mszid);
sendid = new TextView(Main3Activity.this);
sendid.setText(sender_id);
tr1.addView(sendid);
receid = new TextView(Main3Activity.this);
receid.setText(receiver_id);
tr1.addView(receid);
mszcontent = new TextView(Main3Activity.this);
mszcontent.setText(message_content);
tr1.addView(mszcontent);
mszdate = new TextView(Main3Activity.this);
mszdate.setText(message_date);
tr1.addView(mszdate);
myTable1.addView(tr1);
super.onPostExecute(result);
}
}
The program runs and print the first record, but there are 5 records that I'm trying to print. As it's printing out of the loop so it's not printing all records. I'm not sure how to print in Table with loop.
You should be saving all the records in the first place. Here's your problem,
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject message = jsonArray.getJSONObject(i);
message_id =""+message.getInt ("message_id");
sender_id =""+message.getInt ("sender_id");
receiver_id =""+message.getInt("receiver_id");
message_content = message.getString("message_content");
message_date = message.getString("message_date");
}
In this code, you are actually over-writing the previously parsed valued from the previous JSON object. Eventually, what you are printing is the last record.
You should use an ArrayList and save all the records and then display them in your table using a for loop on the ArrayList.
anyone knows why InputStream responseBody = conn.getInputStream(); gives me null ?
basically, the error here is in the first few lines of code.
I have a restful API XML link that i am trying to parse as a JSON object.
And the logcat isn't being very helpful.
Any help would be greatly appreciated
thank you
ArrayList<Camera> cameras = new ArrayList<>();
try {
url = new URL("http://192.168.1.6:50323/Cam_Sql/webresources/com.mycompany.cam_sql.camerasfrench/1/250");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection conn = null;
try {
conn = url.openConnection();
InputStream responseBody = conn.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
JSONObject jsonObj = null;
jsonObj = XML.toJSONObject(responseBodyReader.toString());
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginObject(); // Start processing the JSON object
String cameraLong = null;
String cameraId = null;
String cameraName = null;
String cameraLat = null;
while (jsonReader.hasNext()) { // Loop through all keys
String key = jsonReader.nextName(); // Fetch the next key
if (key.equals("camId")) { // Check if desired key
// Fetch the value as a String
cameraId = jsonReader.nextString();
} else if (key.equals("camName")) {
cameraName = jsonReader.nextString();
} else if (key.equals("cameraLong")) {
cameraLong = jsonReader.nextString();
} else if (key.equals("cameraLat")) {
cameraLat = jsonReader.nextString();
cameras.add(new Camera(cameraName, cameraId, cameraLong, cameraLat));
// Do something with the value
// ...
break; // Break out of the loop
} else {
jsonReader.skipValue(); // Skip values of other keys
}
}
} catch (JSONException e) {
System.out.println(e.toString());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String db = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection dbCon = DriverManager.getConnection("jdbc:jtds:sqlserver://traffic-cam.database.windows.net:1433/Android;user=tyler#traffic-cam;password=Password!;");
// db = dbCon.toString();
int i = 0; //iterator
int rows = 0;
Statement stmt = dbCon.createStatement();
String query = "SELECT COUNT(*) FROM CamerasFrench;";
ResultSet rs = stmt.executeQuery(query);
if(rs.next()){
rows = Integer.parseInt(rs.getString(1)); //gets the amount of rows in database
}
//camInfo = new String[rows][4];
stmt = dbCon.createStatement();
query = "SELECT * FROM CamerasFrench;";
rs = stmt.executeQuery(query);
while(rs.next()){ //goes through every row, puts the data into the 2d array
String cameraName = rs.getString("cam_name");
String cameraLong = rs.getString("cam_longitude");
String cameraLat = rs.getString("cam_latitude");
String cameraId = rs.getString("cam_id");
if (getResources().getConfiguration().locale.getLanguage() == "fr") {
cameraName = rs.getString("cam_frName");
}
cameras.add(new Camera(cameraName, cameraId, cameraLong, cameraLat));
//i++;
//System.out.println("List Size: "+cameras.size());
}
}
catch (Exception e){
System.out.println(e.getMessage());
}
*/
if (cameras.size() > 0) {
Collections.sort(cameras, new Comparator<Camera>() {
#Override
public int compare(final Camera object1, final Camera object2) {
return object1.getCameraName().compareTo(object2.getCameraName());
}
});
}
return cameras;
}
First of all sorry for bad English.
Basically, null pointer exception is very easy to find where this error came from.
Check your connection is successfully connected or not.
below is reference code.
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
// this is option.
urlConnection.setReadTimeout(30000);
urlConnection.setConnectTimeout(30000);
urlConnection.setRequestMethod("GET");
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Content-Type", "application/json");
int responceCode = urlConnection.getResponseCode();
if (responceCode == HttpURLConnection.HTTP_OK) {} // using here. conn.getInputStream()
In debugging i can see that it puts everything what i need into the sb StringBuilders, but after the second sb the data just disapears and what was prevously written into the safety_string gets deleted aswell, don't know why.
Here is the whole code, changed it a little since i posted.
Still the same, it's not an out of scope, because the result of getting_kat i do receive, only the result of getting_ter is missing.
#Override
public String doInBackground(String... voids) {
String result="";
result=getting_kat();
result+=getting_ter();
//Making sure it gets put into the safety string
safety_string=result;
return result;
}
public String getting_kat(){
String result="";
String resultkat = null;
String connstr = "My connection string";
try {
URL url = new URL(connstr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
InputStream ips = http.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(ips, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = "";
//Line by Line reading the data from php
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
//String it together into one line
resultkat = sb.toString();
//Adding a separator for later split
result=resultkat+"#KATEGORIA/TERMEK#";
br.close();
ips.close();
http.disconnect();
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
}
public String getting_ter(){
String result="";
String resultter=null;
String connstr2 = "My connection string 2";
try {
URL url = new URL(connstr2);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
InputStream ips = http.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(ips, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = "";
//Line by Line reading the data from php
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
//String it together into one line
resultter = sb.toString();
result=resultter;
br.close();
ips.close();
http.disconnect();
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
}
I can't see bug in the code. I cleaned it up a bit for you but it should work both before and after my changes. You don't describe what is actually going wrong with it. In debugging you may just be getting timeout on your connection.
public String doInBackground(String... voids) {
String result = getting_kat() + "#KATEGORIA/TERMEK#" + getting_ter();
//Making sure it gets put into the safety string
safety_string = result;
return result;
}
public String getting_kat() {
String result = "";
String connstr = "My connection string";
try {
HttpURLConnection http = connect(connstr);
result = readFromPhp(http);
http.disconnect();
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
}
public String getting_ter() {
String result = "";
String connstr = "My connection string 2";
try {
HttpURLConnection http = connect(connstr);
result = readFromPhp(http);
http.disconnect();
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
}
private HttpURLConnection connect(String connstr) throws IOException {
URL url = new URL(connstr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
return http;
}
private String readFromPhp(HttpURLConnection http) throws IOException {
// try-with-resources - so you don't have to call close()
try (
InputStream ips = http.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(ips, "UTF-8"), 8)
) {
StringBuilder sb = new StringBuilder();
String line;
//Line by Line reading the data from php
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
//String it together into one line
return sb.toString();
}
}
I want to convert a HTTP GET request to a HTTP PATCH request. I am accessing TFS APIs and I want to lock my build automatically by using a patch request.
Currently I am getting all the information by GET method. Now I want to update keepForever from false to true using the HTTP PATCH method. By GET method I am able to do that but now I have to do that by HTTP Patch method.
Can someone help me converting the below code from GET method to POST method?
public class Test_URL_Req {
public static String getURLResponse(String url) {
try {
System.out.println("\nSending 'GET' request to URL : " + url);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
// System.out.println(response);
}
in.close();
return response.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static void main(String[] args) throws JSONException{
String url = "https://tfs.tpsonline.com/IRIS%204.0%20Collection/Main/_apis/build/definitions?api-version=4.1";
//String url1 ="https://tfs.tpsonline.com/IRIS%204.0%20Collection/Main/_apis/build/builds?api-version=4.1&definitions=" + Def_id +"&resultFilter=succeeded&$top=1";
String response = getURLResponse(url);
// String response1 = getURLResponse(url1);
JSONObject obj_JSONObject = new JSONObject(response.toString());
JSONArray obj_JSONArray = obj_JSONObject.getJSONArray("value");
String Def_id=null;
for(int i=0; i<obj_JSONArray.length();i++)
{
JSONObject obj_JSONObject2 = obj_JSONArray.getJSONObject(i);
String value = obj_JSONObject2.getString("name");
String toSearch= "DEVOPS";
if(value.equals(toSearch)){
System.out.println("STATUS:-");
System.out.println(value);
String result =obj_JSONObject2.getString("name");
System.out.println("BUILD NAME");
System.out.println(result);
Def_id = obj_JSONObject2.get("id").toString();
System.out.println("DEFINATION ID");
System.out.println(Def_id);
break;
}
}
if (Def_id != null)
{
String url1 ="https://tfs.tpsonline.com/IRIS%204.0%20Collection/Main/_apis/build/builds?api-version=4.1&definitions=" + Def_id +"&resultFilter=succeeded&$top=1";
String response1 = getURLResponse(url1);
JSONObject obj_JSONObject1 = new JSONObject(response1.toString());
JSONArray obj_JSONArray1 = obj_JSONObject1.getJSONArray("value");
String Build_id=null;
for(int i=0; i<obj_JSONArray1.length();i++)
{
JSONObject obj_JSONObject2 = obj_JSONArray1.getJSONObject(i);
String value = obj_JSONObject2.getString("result");
//String value = obj_JSONObject2.get("id").toString();
//System.out.println(value);
String toSearch1= "succeeded";
if(value.equals(toSearch1)){
System.out.println("#######################################");
System.out.println("RESULT");
System.out.println(value);
String result =obj_JSONObject2.getString("status");
System.out.println("STATUS");
System.out.println(result);
Build_id = obj_JSONObject2.get("id").toString();
System.out.println("BUILD ID");
System.out.println(Build_id);
//boolean keepForever =obj_JSONObject2.getBoolean("keepForever");
//if(keepForever == false)
//{
// keepForever=true;
//}
// System.out.println(keepForever);
}
}
if (Build_id != null)
{
String url2= "https://tfs.tpsonline.com/IRIS%204.0%20Collection/Main/_apis/build/builds?api-version=4.1&buildNumber=" + Build_id;
String response2 = getURLResponse(url2);
JSONObject obj_JSONObject2 = new JSONObject(response2.toString());
JSONArray obj_JSONArray2 = obj_JSONObject2.getJSONArray("value");
for(int i=0; i<obj_JSONArray2.length();i++)
{
JSONObject obj_JSONObject3 = obj_JSONArray2.getJSONObject(i);
String value = obj_JSONObject3.getString("result");
//String value = obj_JSONObject2.get("id").toString();
//System.out.println(value);
String toSearch1= "succeeded";
if(value.equals(toSearch1)){
boolean keepForever =obj_JSONObject3.put("keepForever", false) != null;
if(keepForever == false)
{
keepForever = true;
}
System.out.println("#######################################");
System.out.println(keepForever);
}
}
}
}
}
}
You can just use the below to build PATCH request. However, you should also make sure that your server supports PATCH as its generally unsupported.
public static String getPatchResponse( String url){
try {
System.out.println("\nSending 'PATCH' request to URL : " + url);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("PATCH");
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
//System.out.println(response);
}
in.close();
return response.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}