com.webstersmalley.tv.comms.HttpComms Maven / Gradle / Ivy
/*
* Copyright 2013 Webster Smalley
*
* 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 com.webstersmalley.tv.comms;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
@Repository("httpComms")
public class HttpComms implements Comms {
private final Logger logger = LoggerFactory.getLogger(getClass());
public String getURLAsString(String resource) {
logger.debug("serving: {}", resource);
try {
URL url = new URL(resource);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setRequestProperty("User-Agent", "blah");
uc.connect();
InputStream is = uc.getInputStream();
String contents = IOUtils.toString(is);
IOUtils.closeQuietly(is);
return contents;
} catch (Exception e) {
throw new RuntimeException("Error getting url", e);
}
}
public String getResourceByRawHttp(URL url, String request) {
try {
Socket s = new Socket(url.getHost(), url.getPort());
IOUtils.write(request, s.getOutputStream());
return IOUtils.toString(s.getInputStream());
} catch (IOException e) {
logger.error("Comms error: " + e.getMessage(), e);
throw new RuntimeException("Comms error: " + e.getMessage(), e);
}
}
}