Skip to content

Instantly share code, notes, and snippets.

@ricdex
Last active December 22, 2015 09:18
Show Gist options
  • Save ricdex/6450682 to your computer and use it in GitHub Desktop.
Save ricdex/6450682 to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
public class HTTPJsonEngine {
public static String getJSONHttpGet(String url, Map<String, String> headers) throws Exception {
StringBuilder builder = new StringBuilder();
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
addHeaderToken(httpget, headers);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
public static String postJSONHttp(String url, Map<String, String> headers, String data) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
StringBuilder builder = new StringBuilder();
StringEntity se = new StringEntity(data,HTTP.UTF_8);
httppost.setEntity(se);
addHeaderToken(httppost, headers);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
private static void addHeaderToken(HttpRequestBase httpCall,Map<String, String> headers)
{
if(headers!=null)
{
for(String key : headers.keySet())
{
httpCall.addHeader(key, headers.get(key));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment