Java tutorial
/** * Copyright 2012-2014 Ravello Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package httputils; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.util.EntityUtils; public class HttpUtil { public static void setJsonHeaders(HttpRequest req) { req.addHeader("Content-type", "application/json"); req.addHeader("Accept", "application/json"); } public static boolean verifyResponseWithoutConsuming(HttpResponse response) { return !(response.getStatusLine().getStatusCode() >= 400); } /** * * @param response * @return true if no error, false if error */ public static boolean verifyResponseAndConsume(HttpResponse response) { boolean retVal = verifyResponseWithoutConsuming(response); EntityUtils.consumeQuietly(response.getEntity()); return retVal; } public static JsonObject convertResponseToJson(HttpResponse response) throws ParseException, IOException { InputStream in = response.getEntity().getContent(); JsonReader reader = Json.createReader(in); JsonObject jObj = reader.readObject(); reader.close(); in.close(); return jObj; } public static JsonObject convertStringToJson(String jstring) { StringReader in = new StringReader(jstring); JsonReader reader = Json.createReader(in); JsonObject jObj = reader.readObject(); reader.close(); in.close(); return jObj; } private static JsonObject convertSomethingToJson(InputStream is) { JsonReader reader = Json.createReader(is); JsonObject jObj = reader.readObject(); reader.close(); return jObj; } }