Created
September 8, 2015 15:25
-
-
Save MBtech/f1e710c2317881445545 to your computer and use it in GitHub Desktop.
A rest client example using the apache http library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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