Get JSON response from Jenkins API in java which requires sign in - json

I want to read JSON response coming from jenkins API to read last build details. I am using http://jenkins_server/job/job_name/lastBuild/api/json. When I type this URL in browser, I need to sign in to my Jenkins job and after that I get proper json response.
I have written a java code to read JSON response from same Jenkins API. But I get "Server returned HTTP response code: 403" as I have not handled the authentication part in code.
public class GetJSONResponse {
public static void main(String[] args) throws MalformedURLException, IOException, JSONException {
InputStream is = new URL("http://jenkins_server/job/job_name/lastBuild/api/json").openStream();
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);
}
JSONObject json = new JSONObject(sb.toString());
System.out.println(json.toString());
}
}
I searched alot on how to get JSON response from jenkins API which reqiures authentication , but didn't find anything useful. How do I add authentication part in my code? Can anybody please help me with this?
Thanks in advance.

I resolved my problem after changing the jenkins config.xml "useSecurity" fileld.
Change <useSecurity>true</useSecurity> to <useSecurity>false</useSecurity>
And I got correct JSON response.

Related

Not able to send JSON Array with jersey Response, "getting error Generating incomplete JSON "

I am trying to send JSONArray with Jersey response. Here is the sample code
This looks easy but I am getting the bellow error
org.eclipse.yasson.internal.Marshaller marshall
SEVERE: Generating incomplete JSON
#GET
#Path("/test")
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_JSON})
public Response test(){
JSONArray array = new JSONArray();
array.put("123");
array.put("456");
array.put("789");
return Response.ok(array).build();
}
I tried this also, but no luck
#GET
#Path("/test")
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_JSON})
public Response test(){
JSONArray array = new JSONArray();
array.put("123");
array.put("456");
array.put("789");
JSONObject obj = new JSONObject();
obj.put("Array", array);
return Response.ok(obj).build();
}
Dependencies are fine, because I am able to run other service,
I did google for this error but could not find proper solution for this.
What causes this errororg.eclipse.yasson.internal.Marshaller marshall SEVERE: Generating incomplete JSON to occur?
How do we handle it?
Update 1 :
When I send the array as String it did work
return Response.ok(array.toString()).build();
I am surprise, is jersey not able to recognize JSONOnject or JSONArray?

How to make JSON PUT request through Codename one API

I'm not able top figure out JSON put request from codename one api. I didnt find any example to make this request.
Questions:
1. I'm not sure whether I have to send the content length parameter. If yes, how can I send that?
2. I have to send the request body with just "true" nothing else. There is no key and value to use req.addArgument() method.
3. Do I have to use buildRequestBody() method to override the request. Can you provide an example?
4. How to verify the result after receiving the response.
Any help can be appreciated.
Thanks.
Please find the code below.
req.setUrl(identityUrl );
req.setPost(false);
req.setHttpMethod("PUT");
req.setContentType("application/json");
req.addRequestHeader("authorization", token);
req.addArgument("Content-Length", "4");
req.setReadResponseForErrors(true);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
NetworkManager.getInstance().addToQueueAndWait(req);
d.dispose();
JSONParser parser = new JSONParser();
Map map2 = null;
try {
map2 = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(req.getResponseData()), "UTF-8"));
} catch (IOException ex) {
ex.printStackTrace();
}
If you want the content to be embedded wholly you need to override the buildRequestBody method. Notice that post needs to be true for the body to be called.
I don't think you need content-length:
req = new ConnectionRequest(identityUrl) {
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(json.getBytes("UTF-8"));
}
protected void readResponse(InputStream input) throws IOException {
map2 = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
}
protected void postResponse() {
// response completed, this is called on the EDT do the application logic here...
}
};
req.setPost(true);
req.setHttpMethod("PUT");
req.setContentType("application/json");
req.addRequestHeader("authorization", token);
req.setReadResponseForErrors(true);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
req.setDisposeOnCompletion(d);
NetworkManager.getInstance().addToQueue(req);
Notice that I no longer need to close streams or handle IOException as the connection request does everything for me. Also notice the read/build methods are called on the network threads and not on the EDT so you need to do the rest of the flow in the postResponse.

how to include the json file in request body using httpClient?

how to include the json file in request body using httpClient?
My Json:
{
"products": {
"product": {
"sku": "100",
"varientsku": "0",
"mrp": "5,300",
"webprice": "5,220",
”inventory”: ”25”
}
}
}
My code:
public static void main(String args[])
{
uri=//url
JSONObject json=new JSONObject();
json.put("sku", "100");
json.put("mrp", "12121");
json.put("inventory", "2525");
JSONObject product=new JSONObject();
product.put("product", json);
JSONObject products=new JSONObject();
products.put("products", product);
HttpPost postRequest=new HttpPost(uri);
postRequest.addHeader("accept", "application/json");
postRequest.setHeader("ContentType", "application/json");
postRequest.setEntity(new StringEntity(products.toString(), "UTF-8"));
HttpResponse response=httpClient.execute(postRequest);
}
Read the file into memory and json_encode it.
in javascript:
var json = JSON.stringify(file);
in c#:
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(file);
Then what you have is a string with all the information in the file. Pass it as you would any string information. Then when you handle it (presumably in php?), json_decode it,
$jsonObject = json_encode($data['body']);
I hope this helps with your question. If not, please provide more information like what language you are using, and for what purpose you are using httpClient. The more information, the better.
~~UPDATED UPON REQUEST~~
For Java, it appears that people recommend using Apache's HttpClient library found: HERE, look at the first few chapters of the tutorial to see if it's what you want. You can download the library from them on that site as well.
For simple requests, some people will use HttpURLconnection by oracle (found HERE) example:
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream stream = connection.getInputStream(); //read the contents using an InputStreamReader
I found this information HERE

apache httpclient- most efficient way to read response

I'm using apache httpcompnonents library for httpclient. I want to use it in a multithreaded application where number of threads are going to be really high and there would be frequent http calls. This is the code I'm using to read the response after execute call.
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity);
I just want to confirm that is it the most efficient way of reading the response?
Thanks,
Hemant
This in fact represents the most inefficient way of processing an HTTP response.
You most likely want to digest the content of the response into a domain object of a sort. So, what is the point of buffering it in-memory in a form of a string?
The recommended way to deal with response processing is by using a custom ResponseHandler that can process the content by streaming it directly from the underlying connection. The added benefit of using a ResponseHandler is that it completely relieves from dealing with connection release and resource deallocation.
EDIT: modified the sample code to use JSON
Here's an example of it using HttpClient 4.2 and Jackson JSON processor. Stuff is assumed to be your domain object with JSON bindings.
ResponseHandler<Stuff> rh = new ResponseHandler<Stuff>() {
#Override
public Stuff handleResponse(
final HttpResponse response) throws IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(
statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
JsonFactory jsonf = new JsonFactory();
InputStream instream = entity.getContent();
// try - finally is not strictly necessary here
// but is a good practice
try {
JsonParser jsonParser = jsonf.createParser(instream);
// Use the parser to deserialize the object from the content stream
return stuff;
} finally {
instream.close();
}
}
};
DefaultHttpClient client = new DefaultHttpClient();
Stuff mystuff = client.execute(new HttpGet("http://somehost/stuff"), rh);

Retrieving JSON Object Literal from HttpServletRequest

I am writing code that needs to extract an object literal posted to a servlet. I have studied the API for the HttpServletRequest object, but it is not clear to me how to get the JSON object out of the request since it is not posted from a form element on a web page.
Any insight is appreciated.
Thanks.
are you looking for this ?
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} finally {
reader.close();
}
System.out.println(sb.toString());
}
This is simple method to get request data from HttpServletRequest
using Java 8 Stream API:
String requestData = request.getReader().lines().collect(Collectors.joining());
make use of the jackson JSON processor
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(request.getInputStream(),Book.class);
The easiest way is to populate your bean would be from a Reader object, this can be done in a single call:
BufferedReader reader = request.getReader();
Gson gson = new Gson();
MyBean myBean = gson.fromJson(reader, MyBean.class);
There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request
String jsonString = IOUtils.toString(request.getInputStream());
Then you can do whatever you want, convert it to JSON or other object with Gson, etc.
JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
If you're trying to get data out of the request body, the code above works. But, I think you are having the same problem I was..
If the data in the body is in JSON form, and you want it as a Java object, you'll need to parse it yourself, or use a library like google-gson to handle it for you. You should look at the docs and examples at the project's website to know how to use it. It's fairly simple.
Converting the retreived data from the request object to json object is as below using google-gson
Gson gson = new Gson();
ABCClass c1 = gson.fromJson(data, ABCClass.class);
//ABC class is a class whose strcuture matches to the data variable retrieved