Skip to content

Instantly share code, notes, and snippets.

@MBtech
Created September 8, 2015 15:25
Show Gist options
  • Save MBtech/f1e710c2317881445545 to your computer and use it in GitHub Desktop.
Save MBtech/f1e710c2317881445545 to your computer and use it in GitHub Desktop.
A rest client example using the apache http library
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.learningcurve.mb.restclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
/**
* Example of how to use rest apis with Java using
* apache http library
* @author mb
*/
public class restTest {
public static void main(String[] args) throws IOException {
HttpClientBuilder httpcb = HttpClientBuilder.create();
CloseableHttpClient httpclient = httpcb.build();
HttpPost req = new HttpPost("http://jsonplaceholder.typicode.com/posts");
//HttpGet req = new HttpGet("http://jsonplaceholder.typicode.com/posts/1");
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("title", "foo"));
postParameters.add(new BasicNameValuePair("body", "bar"));
postParameters.add(new BasicNameValuePair("userId", "1"));
req.setEntity(new UrlEncodedFormEntity(postParameters));
CloseableHttpResponse resp = httpclient.execute(req);
HttpEntity entity = resp.getEntity();
InputStream in = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment