How to solve this imports in Android studio - url

How to solve this, help me out I'm new

Please explain your question... If you want to fetch from http, below code will help you. you may need to add some libraries too.
HttpClient httpclient = new DefaultHttpClient();
Httppost httppost = new HttpPost("www.example.com");
HttpResponse response = httpclient.execute(httppost);
entity = response.getEntity();
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 result = sb.toString();
JSONObject jsonObj = new JSONObject(result);
continue your code after this...

Add the libraries to the gradle file.
Look for this line:
dependencies {
...
}
and add this:
dependencies {
...
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpcore:4.4'
}

Related

Why does this script cause problems only on Jenkins?

I had to add a job in a multibranch pipeline.
The goal was to automatically install a plugin in jira.
The code runs perfectly fine because I tested it in a Unit Test.
But when I put it as a scripted pipeline on Jenkins, it does not do what it should do.
The goal is to install the plugin on jira, but when I run it on Jenkins it will not be installed.
Also I do not get any json Response, which I get in my JUnit Test.
I really do not know what is different on Jenkins. I already found it weird that I have to approve every single method in my script. Did someone have a similar issue on jenkins before.
I really appreciate your help.
#Test
public void test_install_plugin() throws IOException {
String jsonBody = "{\"pluginUri\": \"http://myServer/job/element/job/mybranch\", \"pluginName\": \"myPlugin\"}";
String token = "-6485649001990379871";
String jiraPath="myServer/rest/plugins/1.0/";
String query = "token="+token;
String url = jiraPath+"?"+query;
URL jiraURL = new URL(url);
HttpURLConnection jiraURLConnection = (HttpURLConnection)jiraURL.openConnection();
jiraURLConnection.setDoOutput(true);
jiraURLConnection.setDoInput(true);
jiraURLConnection.setRequestProperty ("Content-Length",String.valueOf(jsonBody.length()));
jiraURLConnection.setRequestProperty ("Accept", "application/json");
jiraURLConnection.setRequestProperty ("Content-Type", "application/vnd.atl.plugins.install.uri+json");
jiraURLConnection.setRequestProperty ("Authorization", "Basic YWRXXXXXXtaW4=");
jiraURLConnection.setRequestMethod("POST");
OutputStream os = null;
try {
os = jiraURLConnection.getOutputStream();
byte[] input = jsonBody.getBytes("utf-8");
os.write(input, 0, input.length);
os.flush();
}
catch(IOException ex)
{
System.out.println("Exception: " + ex.getMessage());
}
finally
{
os.close();
System.out.println("responseCode of install request: " + jiraURLConnection.getResponseCode());
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(jiraURLConnection.getInputStream(), "utf-8"));
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("Response: " + response.toString());
}
catch(IOException ex)
{
System.out.println("Exception: " + ex.getMessage());
}
finally
{
br.close();
jiraURLConnection.disconnect();
}
}

add parameters in JSON FORM to HttpURLConnection using POST

Well the best vote for adding parameters to HttpURLConnection is in this post
But the answer of it is explain about how to adding parameter that have the form something like this
--> "username=usernameValue?password=passwordValue"<--
REMEMBER the parameter can have the form like JSON Object and the answer form the link can make you lost of direction if you dont know about JSON Parameter for POST.
Then this is the best answer from me that i can provide.
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
JSONObject urlParameter = new JSONObject();
urlParameter.put("username", usernameValue);
urlParameter.put("password", passwordValue);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(urlParameter.toString());
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
StringBuilder sb;
sb = new StringBuilder();
if (responseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
} else {
System.out.println(conn.getResponseMessage());
}
String result = sb.toString();
Please enlighten me if you have better solution. TY

Load More data by using HTTPURLConnection in java

In my program , I read data by using HTTPURLConnection for example
URL url = new URL("https://twitter.com/search?q="+kw+"%20lang%3Aeng%20"+"&src=typd&lang=en");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append("\n");
}
String html = builder.toString();
The problem is only reading data on response page , but I need to read all data that can be retrieved
How I can Load more data in result page

sending json data to server in blackberry

In my application i have to integrate API. I am not getting code for how to check whether internet is available or not. How to send JSON Data to server. Please help me out. As in android we call API in AsyncTask class. In blackberry i did not found like this.
Suggest me some link or ideas so that i can integrate code. I am googling. But did not getting result .
What I have tried is here:
JSONObject postData = new JSONObject();
postData.put("userId", "24");
postData.put("messageTime","06:00:00");
postData.put("language", language[lang_Ocf.getSelectedIndex()]);
System.out.println("********json********"+postData);
ConnectionFactory conFactory = new ConnectionFactory();
ConnectionDescriptor conDesc = null;
try
{
conDesc = conFactory.getConnection(url+";deviceside=true");
}
catch(Exception e)
{
System.out.println(e.toString()+":"+e.getMessage());
}
String response = ""; // this variable used for the server response
// if we can get the connection descriptor from ConnectionFactory
if(null != conDesc)
{
try
{
HttpConnection connection = (HttpConnection)conDesc.getConnection();
//set the header property
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Length", Integer.toString(postData.length()));
connection.setRequestProperty("Content-Type","application/json");
OutputStream out = connection.openOutputStream();
out.write(postData.get);
out.flush();
out.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK){
InputStream in = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int read = -1;
while((read = in.read())!= -1)
buf.append((char)read);
response = buf.toString();
}
Dialog.inform(response);
connection.close();
} catch(Exception e) {
}
}
return response;
Thanks
I solved this problem
Error:
Error: Cannot run program "jar": CreateProcess error=2, The system cannot find the file specified Packaging project HelaBibleWhereUR failed (took 10.715 seconds)
I simply put jar.exe that is under java bin folder in the jre bin folder.

How to handle SQL Query CommandTimeout in C# 2.0

I have got below code in c#.
SqlConnection conn = new SqlConnection("Data Source=MANOJ-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=False;User Id=sa;Password=Manoj;");
conn.Open();
if (conn != null)
{
//create command
SqlCommand cmd = new SqlCommand("dbo.GETTridionLinkData", conn);
cmd.Parameters.AddWithValue("#PageID", "637518");
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 500;
StringBuilder sbXML = new StringBuilder();
//Adding Root node
sbXML.Append("<TridionLinks>");
//Reading all the values of Stored procedure return
using (XmlReader reader = cmd.ExecuteXmlReader())
{
while (reader.Read())
{
sbXML.Append(reader.ReadOuterXml().Replace("//", "/"));
}
}
//Closing the root node tag
sbXML.Append("</TridionLinks>");
XmlDocument xDoc = new XmlDocument();
//Loading string xml in XML Document
xDoc.LoadXml(sbXML.ToString());
}
In above code you can see that, I have set the cmd.CommandTimeout = 500;, now I want to give user an error message if the timeout is more than this or you can say database is down.
Please suggest!!
Please refer to
How to catch SQLServer timeout exceptions
The question has already been answered..
To improve coding, you can use
try{
using (sqlconnection Conn = new SqlConnection("Data Source=MANOJ-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=False;User Id=sa;Password=Manoj;"){
...
}
}catch(sqlException ex){
if (ex.Number == -2) {
//return your message to the control or display the error
}
}
well just an example..

Resources